Python file modify, replace, delete

First, modify the original contents of the file mode:

# ! / Usr / bin / env Python 
# - * - Coding: utf8 - * - 


old_str = " aaa "  # old file content field 
new_str = " bbb "  # To change the field 
file_data = '' 
with Open ( ' / opt / 1.txt ' , ' R & lt ' , 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)

Two, python using regular expressions to replace the file content replacement method 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")

 

Guess you like

Origin www.cnblogs.com/QQmini/p/11427089.html