#!/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)
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")
原文:https://www.cnblogs.com/QQmini/p/11427089.html