如何在 Python 中讀取檔案(文字和 JSON)
了解如何在 Python 中讀取檔案。掌握with open語句、readline、readlines以及安全性處理檔案異常。
概述
文件處理是任何 Python 開發人員的基本技能。從文件中讀取資料可讓您處理文字文件、配置、日誌、資料庫和結構化資料集。 Python 透過其內建的「open()」函數讓檔案操作變得非常簡單。
處理文件時,最關鍵的最佳實踐是使用「with」語句,它會建立一個上下文管理器。 `with open(...)` 模式保證一旦執行離開區塊,檔案就會被安全、正確地關閉,即使內部發生異常也是如此。忘記關閉檔案可能會導致記憶體洩漏、檔案損壞以及鎖定其他系統進程的資源。
Python 提供了幾種在開啟檔案後讀取資料的方法。 `.read()` 方法將檔案的全部內容作為單一字串傳回。 `.readline()` 方法讀取一行,非常適合迭代無法放入記憶體的巨型檔案。 `.readlines()` 方法讀取所有行並將它們作為字串清單傳回。了解使用哪種方法可以防止記憶體耗盡並使您的程式更具可擴展性。
程式碼和執行輸出
這個腳本示範如何使用上下文管理器、逐行讀取和錯誤處理來安全地讀取檔案內容。
read_file.py
在編輯器中嘗試# Writing a dummy file first
with open("sample.txt", "w") as f:
f.write("Line 1: Welcome to PyRun!\nLine 2: Python runs in the browser.\nLine 3: Clean and simple.")
# 1. Read entire file contents
with open("sample.txt", "r") as file:
content = file.read()
print("--- Entire File ---")
print(content)
# 2. Read line-by-line (Memory efficient for large files)
print("\n--- Line by Line ---")
with open("sample.txt", "r") as file:
for line in file:
print("Read line:", line.strip())端子輸出
--- Entire File ---
Line 1: Welcome to PyRun!
Line 2: Python runs in the browser.
Line 3: Clean and simple.
--- Line by Line ---
Read line: Line 1: Welcome to PyRun!
Read line: Line 2: Python runs in the browser.
Read line: Line 3: Clean and simple.逐步實施
- 使用 with open("filename", "r") as file 語句安全地開啟檔案進行讀取。
- 呼叫 file.read() 將整個檔案內容載入到變數中。
- 使用 for 迴圈直接迭代文件對象,以有效地逐行讀取它。
- 始終指定編碼(例如,encoding="utf-8")以實現國際字元相容性。
常見問題解答
為什麼要使用with語句來開啟檔案?
with 語句建立一個上下文管理器,即使發生錯誤,退出區塊時也會自動關閉檔案。
如何處理 FileNotFoundError?
將 open() 語句包裝在 try- except 區塊中,捕獲 FileNotFoundError: try: with open(...) ... except FileNotFoundError: print("File not find!")。
相關主題
推薦的 Python 資源
透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。