您的位置:首页 > 编程语言 > Python开发

python修改文件内容

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

#原文件: 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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息