1. 程式人生 > >Python 檔案修改

Python 檔案修改

# 需求: 把好人換成sb
# 必須:
#   1. 先從檔案中讀取內容
#   2. 把要修改的內容進行修改
#   3. 把修改好的內容寫人一個新檔案
#   4. 刪除掉原來的檔案
#   5. 把新檔案重新命名成原來的檔案的名字

# 匯入os模組  os表示作業系統
import os

f = open("誇一誇alex", mode="r", encoding="utf-8")
f2 = open("誇一誇alex_副本", mode="w", encoding="utf-8")

# with會自動的幫我們關閉檔案的連結
with open("誇一誇alex", mode="r", encoding="utf-8") as f, \
     open("誇一誇alex_副本", mode="w", encoding="utf-8") as f2:

    for line in f:
        if "好人" in line:
            line = line.replace("好人", "sb")
        f2.write(line)

# time.sleep(3) # 程式暫停3秒

# 刪除原來檔案
os.remove("誇一誇alex")

# 重新命名副本為原來的檔名
os.rename("誇一誇alex_副本", "誇一誇alex")
f.close()
f2.flush()
f2.close()