1. 程式人生 > 程式設計 >python修改檔案內容的3種方法詳解

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,new_str):
  """
  將替換的字串寫到一個新的檔案中,然後將原檔案刪除,新檔案改為原來檔案的名字
  :param file: 檔案路徑
  :param old_str: 需要替換的字串
  :param new_str: 替換的字串
  :return: None
  """
  with open(file,encoding="utf-8") as f1,open("%s.bak" % file,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,new_str):

  with open(file,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")

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。