程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了查找、替换和添加新行到文本块大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决查找、替换和添加新行到文本块?

开发过程中遇到查找、替换和添加新行到文本块的问题如何解决?下面主要结合日常开发的经验,给出你关于查找、替换和添加新行到文本块的解决方法建议,希望对你解决查找、替换和添加新行到文本块有所启发或帮助;

我对 Python 还是个新手,我的代码基本上都是婴儿变种人! 我一直在努力的一件事是以这种方式编辑文本文件: 1- 搜索特定字符串 2-如果存在,如果与预期不匹配,则替换它。 3- 如果不存在,将其添加到最后一行。

在我的头撞到墙上几个小时后,我无法做到,所以我只是想出了一些现在可以完成工作的东西,这就是您在下面看到的代码。 你们中的任何一个巫师都会向我展示更优雅的解决方案吗?漂亮请...

**Text:**

Sunset_setTings {
 inputs 3
 lifetime 4
 speed 24
 xpos -415
 ypos 949
 focal_type edges
}



**Code:**


focal_type_v = 'points'
found = false
with open("4.txt","r") as f:
    lines = f.readlines()
    for n in lines:
        if "focal_type" in n:
            found = True


    if not found:
        for index,line in enumerate(lines):
            if line.startswith("ypos"):
                break
        lines.insert(index," focal_type " + focal_type_v+ "\n")

with open("4.txt","w") as f:
    contents = f.writelines(lines)

if found:
    fin = open("4.txt","rt")
    data = fin.read()
    if 'focal_type faces' in data:
        data = data.replace('focal_type faces','focal_type ' + focal_type_v)


    elif 'focal_type points' in data:
        data = data.replace('focal_type points','focal_type ' + focal_type_v)

    elif 'focal_type edges' in data:
        data = data.replace('focal_type edges','focal_type ' + focal_type_v)

    elif 'focal_type bBox' in data:
        data = data.replace('focal_type bBox','focal_type ' + focal_type_v)

    else:
        data = data.replace('SELEcted true','focal_type ' + focal_type_v)



    fin.close()
    fin = open("4.txt","wt")
    fin.write(data)
    fin.close()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

大佬总结

以上是大佬教程为你收集整理的查找、替换和添加新行到文本块全部内容,希望文章能够帮你解决查找、替换和添加新行到文本块所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。