python 修改檔案內容3種方法

2021-08-30 04:46:02 字數 1398 閱讀 4094

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

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", "測試")

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

用python修改檔案內容修改txt內容的3種方法

用python修改檔案內容修改txt內容的3種方法 方法一 修改原檔案方式 def updatefile file old str,new str 替換檔案中的字串 param file 檔名 param old str 就字串 param new str 新字串 return file data ...

用python修改檔案內容修改txt內容的3種方法

用python修改檔案內容修改txt內容的3種方法 方法一 修改原檔案方式 def updatefile file,old str,new str 替換檔案中的字串 param file 檔名 param old str 就字串 param new str 新字串 return file data ...

使用python 修改檔案內容

做嵌入式時需要把windows 下的 ads 工程 專案移植到linux 下的gnu專案時候需要做大量重複的修改,比如把 abc equ 1修改為 define abc 1如果用手工乙個個修改很浪費時間,所以就用python指令碼來做這些工作,發現很容易就搞定了 以前遇到類似問題總是用c 來寫,量很...