python修改文件内容

一行行的读取原文件,找到需要修改文件的地方,然后换成修改后的内容,写入新文件,如果原文件不需要了,就可以用新生成的文件覆盖原文件,代码如下:

#原文件: old_file
#新文件: new_file
f = open('old_file', 'r')
f_new = open('new_file', 'w')
for line in f:
    if "context_changed" in line:
        line = line.replace("context_changed", "new_context")
    f_new.write(line)
f.close()
f_new.close()

猜你喜欢

转载自blog.csdn.net/linxi7/article/details/70739660
今日推荐