写函数,, 用户传入修改的文件名, 与要修改的内容, 执行函数, 完成批了修改操作
- def modify_file(filename, old, new): # 定义函数
- import os # 导入文件模块
- with open(filename, 'r', encoding='utf-8') as f_read, open('txt', 'w', encoding='utf-8')as f_write: # 1, 读的模式打开传入的文件, 创建新的文件
- for line in f_read: # 每一行进行迭代, 遍历
- if old in line: # 旧内容在 line 中
- line = line.replace(old, new) # 用新的取代旧的
- f_write.write(line) # 新的 line 写入'txt'文件中
- os.remove(filename) # 文件删除旧的文件
- os.rename('txt', filename) # 把新文件重新命名为 filename
- modify_file('xxx_new', 'alex','seven') # 传入需要修改的文件, 旧的内容, 新的内容
来源: http://www.bubuko.com/infodetail-2870532.html