一、修改原文件内容方式:
1#!/usr/bin/env python 2# -*- coding:utf8 -*- 3 4 5old_str = "aaa" #老文件内容字段 6new_str = "bbb" #要改成字段 7file_data = '' 8with open('/opt/1.txt', 'r', encoding='utf-8') as f: 9 for line in f: 10 if old_str in line: 11 line = line.replace(old_str, new_str) 12 file_data += line 13with open('/opt/1.txt', 'w',encoding='utf-8') as f: 14 f.write(file_data)
二、python 使用正则表达式 替换文件内容 re.sub 方法替换
1import re,os 2def alter(file,old_str,new_str): 3 4 with open(file, "r", encoding="utf-8") as f1,open("%s.bak" % file, "w", encoding="utf-8") as f2: 5 for line in f1: 6 f2.write(re.sub(old_str,new_str,line)) 7 os.remove(file) 8 os.rename("%s.bak" % file, file) 9alter("file1", "admin", "password")
三、python 删除文件一行
1import shutil 2with open('/path/to/file', 'r') as f: 3 with open('/path/to/file.new', 'w') as g: 4 for line in f.readlines(): 5 if '/local/server' not in line: 6 g.write(line) 7shutil.move('/path/to/file.new', '/path/to/file')