黑猴子的家:python 文件备份并替换内容

f1 = open("yesterday","r",encoding="UTF-8")
f2 = open("yesterdaybak","w",encoding="UTF-8")

for line in f1:
    if "多肆意的快乐等我享受" in line:
        line = line.replace("多肆意的快乐等我享受","多肆意的快乐等alex享受")
    f2.write(line)

f1.close()
f2.close()

动态传参

# 动态传参
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()

你可能感兴趣的:(黑猴子的家:python 文件备份并替换内容)