0

我对 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()
4

0 回答 0