如何在 Python 中寫入檔案(寫入和追加)
了解如何使用 Python 將文字寫入檔案。使用安全上下文管理器掌握寫入(“w”)和追加(“a”)模式之間的差異。
概述
將資料寫入檔案是建置腳本、儲存程式狀態、建立日誌或匯出報告時的基本任務。 Python 使用內建的「open()」函數結合控制資料寫入磁碟方式的特定檔案存取模式來簡化檔案輸出。
寫入檔案時,最常見的兩種模式是寫入模式(“w”)和追加模式(“a”)。如果檔案已存在,寫入模式將完全覆蓋該檔案;如果不存在,則建立新檔案。追加模式保留現有內容並直接在文件末端寫入新資料。使用錯誤的模式可能會導致資料意外遺失,因此請謹慎選擇。
與讀取檔案類似,您應該始終使用“with open(...)”語句。這可確保刷新檔案緩衝區並正確關閉檔案句柄,從而節省系統資源並防止資料損壞。為了寫入字串列表,Python 提供了 .writelines() 方法,使批次寫入變得乾淨且有效率。
程式碼和執行輸出
這個腳本演示了在 Python 中覆蓋、追加和檢視檔案。
write_file.py
在編輯器中嘗試# 1. Overwrite a file (or create new) using "w"
with open("output.txt", "w") as file:
file.write("Hello World from Python!\n")
file.write("Writing file content is simple.\n")
# 2. Append new content to the file using "a"
with open("output.txt", "a") as file:
file.write("This line is appended.\n")
# 3. Reading the file back to verify contents
with open("output.txt", "r") as file:
print(file.read().strip())端子輸出
Hello World from Python!
Writing file content is simple.
This line is appended.逐步實施
- 使用 with open('filename', 'w') as file 來覆寫或建立檔案。
- 使用 with open('filename', 'a') as file 在檔案結尾附加文字。
- 呼叫 file.write('string') 將各個文字段寫入檔案。
常見問題解答
如果文件的目錄不存在會發生什麼?
Python 將引發 FileNotFoundError。在寫入檔案之前,必須先使用 os.makedirs 函數建立目錄。
如何將變數或數字寫入檔案?
write() 方法僅接受字串參數。您必須使用 str(num) 轉換數字或使用 f 字串格式化它們。
相關主題
推薦的 Python 資源
透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。