Pythonファイルの変更、置換、削除

3911 ワード

一、原文書の内容方式を修正する:
#!/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")

 
転載先:https://www.cnblogs.com/QQmini/p/11427089.html