Python For Loop搜索和替换

时间:2018-01-03 17:52:33

标签: python for-loop enumerate seek

我正在开发一个文件编辑脚本,它能够根据某些关键字查找文件的某个部分,然后用替代部分替换它下面的部分。重要的是要知道文件的格式非常严格,因此文件之间的差异应该很小或没有。

文件看起来像:

Z1 ; move to next (0)
Q6 ; comment1
X5 Y7 ; point
X6 Y9 ; point
X4 Y8 ; point
Q6 ; comment1
Z2 ; move to next (1)
Q6 ; comment1
X9 Y6 ; point
X4 Y2 ; point
X1 Y7 ; point
Q6 ; comment1

截至目前,我的脚本能够搜索文件并根据;之后的注释执行操作,但我不确定如何删除那里的内容并替换它而不重复遍历整个文件多次

它看起来像这样:

要添加的内容:

A1 B4 ; point
A7 B3 ; point
A1 B7 ; point

因此,脚本会搜索一个' Z1'然后' Q6'如果发生这种情况,请更换' X Y'一节中有新的&A; B'部分。编辑后的版本将如下所示:

 Z1 ; move to next (0)
Q6 ; comment1
A1 B4 ; point
A7 B3 ; point
A1 B7 ; point
Q6 ; comment1
Z2 ; move to next (1)
Q6 ; comment1
X9 Y6 ; point
X4 Y2 ; point
X1 Y7 ; point
Q6 ; comment1

到目前为止我的脚本是:

file_name = "/Users/path/to/file"

with open(file_name, 'r+') as f:
z_val = []
    content = f.readlines()

    for line in content:
        coordinate_set = {}
        if ';' in line:
            if 'Z' in line:
                try:
                    coord, comment = line.strip('\n').split(";")
                    for num in coord.split()[1:]:
                        if 'Z' in num:
                            z_val.append(num)
                except:
                    pass

这很适合找到带有' Z1'的区域。并附加' 1'值列表,但我不确定如何编辑和替换部分。对这些主题的一些研究让我觉得我可能需要使用枚举并寻求在部分列表中向后工作,因为我删除了我不想要的每一行,然后,一旦它在该部分的底部,写在新的部分。

是否有更简单或更有效的方法可以做到这一点?提前谢谢!!!

1 个答案:

答案 0 :(得分:0)

以下是代码的重组版本,它将每个Z之后的数字写入新文件。如果确实需要,您可以在处理后写入同一文件。但写一个新文件通常是一个好主意。

all_z_vals = []
with open(file_name, 'r') as f:
    for line in f.readlines():
        if line[0] == 'Z' and ';' in line:
            z_str, comment = line.split(';')
            z_num = z_str[1:].rstrip()  # rstrip removes right hand side whitespace
            all_z_vals.append(z_num)

with open('my_z_values.txt', 'w') as outfile:
    outfile.writelines(all_z_vals)

旁注:避免使用try-except,因为它准备捕获异常(在这种情况下可以避免),会导致性能下降。