Python 如何在特定匹配时写入文件

Python 如何在特定匹配时写入文件,python,Python,我在“C:\Temp”位置有一个文件,文件名是arun.txt。该文件的内容如下所示 test= pqr= lmn= 我想找到带有“pqr=”的行,并将其修改为“pwr=xyz” 我不太擅长python 但下面的代码我已经写了,但它既没有做任何事情,也没有返回任何错误 f = open('C:\Temp\arun.txt', 'r+') for line in f.readline(): if line == "pqr=":

我在
“C:\Temp”
位置有一个文件,文件名是
arun.txt
。该文件的内容如下所示

test=
pqr=
lmn=
我想找到带有“pqr=”的行,并将其修改为“pwr=xyz”

我不太擅长python

但下面的代码我已经写了,但它既没有做任何事情,也没有返回任何错误

f = open('C:\Temp\arun.txt', 'r+')
        for line in f.readline():
                if line == "pqr=":
                        f.write('pqr=xyz')
如果我在这里做错了什么,请告诉我。

带参数
inplace=True
将您的
print
语句重定向到一个临时文件,该文件将重命名为您的原始文件,以允许就地编辑

with open("input.txt") as input, open("output.txt", "w") as output:
    for line in input:
        if line.startswith("pqr="):
            output.write("pqr=xyz\n")
        else:
            output.write(line)
for line in fileinput.input('Temp', inplace=True):
    line = line.rstrip('\n')
    if line == 'pqr=':
        print line + 'xyz'
    else:
        print line

默认情况下,临时文件是原始文件名
+'.bak'
。这使得程序进程安全,而不是仅仅使用
out.txt
作为文件名,因为您可能决定在另一个文件上运行此程序,这可能会在写入时覆盖
out.txt
。另一种安全的方法是重命名
tempfile.NamedTemporaryFile

您可以使用
将open(“input.txt”)作为输入,open(“output.txt”,“w”)作为输出来组合这两个语句