檔案轉至:
1 def alter(file,old_str,new_str):2 """
3 替換檔案中的字串
4 :param file:檔名
5 :param old_str:就字串
6 :param new_str:新字串
7 :return:
8 """
9 file_data = ""
10 with open(file, "r", encoding="utf-8") as f:
11 for line in f:
12 if old_str in line:
13 line = line.replace(old_str,new_str)
14 file_data += line
15 with open(file,"w",encoding="utf-8") as f:
16 f.write(file_data)
17 18 alter("file1", "09876", "python")
import osdef 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", "測試")
1 import re,os2 def alter(file,old_str,new_str):
3 4 with open(file, "r", encoding="utf-8") as f1,open("%s.bak" % file, "w", encoding="utf-8") as f2:
5 for line in f1:
6 f2.write(re.sub(old_str,new_str,line))
7 os.remove(file)
8 os.rename("%s.bak" % file, file)
9 alter("file1", "admin", "password")
1 def alter(file,old_str,new_str):2 """
3 替換檔案中的字串
4 :param file:檔名
5 :param old_str:就字串
6 :param new_str:新字串
7 :return:
8 """
9 file_data = ""
10 with open(file, "r", encoding="utf-8") as f:
11 for line in f:
12 if old_str in line:
13 line = line.replace(old_str,new_str)
14 file_data += line
15 with open(file,"w",encoding="utf-8") as f:
16 f.write(file_data)
17 18 alter("file1", "09876", "python")
import osdef 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", "測試")
1 import re,os2 def alter(file,old_str,new_str):
3 4 with open(file, "r", encoding="utf-8") as f1,open("%s.bak" % file, "w", encoding="utf-8") as f2:
5 for line in f1:
6 f2.write(re.sub(old_str,new_str,line))
7 os.remove(file)
8 os.rename("%s.bak" % file, file)
9 alter("file1", "admin", "password")
Python 修改檔案
一 有時候我們會遇到在寫入檔案後,其實內容並未被寫到檔案裡面的問題 原因是內容先寫到緩衝區,緩衝區滿時,才寫入磁碟 解決 用f.flush 強制把緩衝區裡面的資料寫到磁碟上 fw open username.txt w fw.write 測試 fw.flush 二 修改檔案簡單直接的方法 repla...
python修改檔案 fileinput
上網查了好多方法都是將檔案一行一行都進來,然後新開乙個檔案指標,將檔案再一行行寫進新檔案裡。感覺不是太好,看到這個fileinput的庫,發現大同小異,不過有一點就是可以在原檔案上修改,不用新開檔案。舉個簡單的例子 我有json檔案1.json是如下格式 1 2 我想把檔案裡面的 換成乙個,可以通過...
python之檔案修改
with open a.txt mode r t encoding utf 8 as f print f.writable f.seek 7,0 f.write sb with open a.txt mode r t encoding utf 8 as f f.seek 3,0 f.write h ...