1. 程式人生 > >python 修改檔案內容3種方法

python 修改檔案內容3種方法

一、修改原檔案方式

 

 def alter(file,old_str,new_str):
     """
     替換檔案中的字串
     :param file:檔名
     :param old_str:就字串
     :param new_str:新字串
     :return:
     """
      file_data = ""
     with open(file, "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(file,"w",encoding="utf-8") as f:
         f.write(file_data)
 
 alter("file1", "09876", "python")

 

二、把原檔案內容和要修改的內容寫到新檔案中進行儲存的方式

2.1 python字串替換的方法,修改檔案內容

 

import os
def alter(file,old_str,new_str):
    """
    將替換的字串寫到一個新的檔案中,然後將原檔案刪除,新檔案改為原來檔案的名字
    :param file: 檔案路徑
    :param old_str: 需要替換的字串
    :param new_str: 替換的字串
    :return: None
    """
    with open(file, "r", encoding="utf-8") as f1,open("%s.bak" % file, "w", encoding="utf-8") as f2:
        for line in f1:
            if old_str in line:
                line = line.replace(old_str, new_str)
            f2.write(line)
    os.remove(file)
    os.rename("%s.bak" % file, file)

alter("file1", "python", "測試")

 

2.2 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")