Python修改文件方法——字符串替换
Posted 无所住心
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python修改文件方法——字符串替换相关的知识,希望对你有一定的参考价值。
#字符串替换
import sys
f = open("yesterday2","r",encoding="utf-8")
f_new = open("yesterday2.bak","w",encoding="utf-8")
find_str = sys.argv[1]
replace_str = sys.argv[2]
for line in f:
if find_str in line:
line = line.replace(find_str,replace_str)
f_new.write(line)
f.close()
f_new.close()
#with执行问了,文件就自动关闭了! 开发规范一行代码不能超过80字符: \
with open("yesterday2","r",encoding="utf-8") as f ,\
open("yesterday2", "r", encoding="utf-8") as f2:
for line in f:
print(line)
以上是关于Python修改文件方法——字符串替换的主要内容,如果未能解决你的问题,请参考以下文章