一、修改原文件内容方式:
#!/usr/bin/env python # -*- coding:utf8 -*- old_str = "aaa" #老文件内容字段 new_str = "bbb" #要改成字段 file_data = '' with open('/opt/1.txt', 'r', encoding='utf-8') as f: for line in f: if old_str in line: line = line.replace(old_str, new_str) file_data += line with open('/opt/1.txt', 'w',encoding='utf-8') as f: f.write(file_data)
二、python 使用正则表达式 替换文件内容 re.sub 方法替换
import re,os def alter(file,old_str,new_str): with open(file, "r", encoding="utf-8") as f1,open("%s.bak" % file, "w", encoding="utf-8") as f2: for line in f1: f2.write(re.sub(old_str,new_str,line)) os.remove(file) os.rename("%s.bak" % file, file) alter("file1", "admin", "password")