如何使用python的元组替换文件中的值?

时间:2018-09-17 15:37:53

标签: python python-3.x tuples

我有这样的元组[(x1,x12),(x2,x22),(x3,x32)..]。 我也有带有未排序代码的txt文件,其中满足x1,x2,x3 ... xn。

我要按以下顺序替换txt文件中的值: x1(旧)-> x12(新),x2(旧)---> x22(新)...

所以...我写了这样的代码:

gen = (x for x in df1 if x[0] != x[1])


for x in gen:

    with open(ei.txt) as f1:
    newText = [f1.read().replace(x[1], x[0])]

    with open(ei2.txt, "w") as f2:
    f2.write(newText)

但是在处理它时出现错误:预期为缩进块。 代码有什么问题?

2 个答案:

答案 0 :(得分:0)

  

期望缩进的块。代码有什么问题?

更正代码缩进。在python中很重要。还要在文本文件名周围加上引号。

gen = (x for x in df1 if x[0] != x[1])

df = []


for x in gen:

    with open("ei.txt") as f1:
        newText = [f1.read().replace(x[1], x[0])]   # <-- Add four spaces

    with open("ei2.txt", "w") as f2:
        f2.write(newText)    # <-- Add four spaces

答案 1 :(得分:0)

您应该只读取一次文件,应用所有更改,然后再次将文件写出。

replacements = [('x', 'y'), ('a', 'b')]

with open('ei.txt') as infile
    text = infile.read()

for target, replacement in replacements:
    text = text.replace(target, replacement)

with open('ei2.txt', 'w+') as outfile:
    outfile.write(text)

如果所有转换都替换为单个字符,则可以使用str.translate