Python 文件處理簡介

Patricia Arquette
發布: 2024-10-19 22:17:01
原創
789 人瀏覽過

Introduction to File Handling in Python

檔案處理是使用 Python 最重要的方面之一。無論您是閱讀文字文件、編寫日誌、處理 CSV 文件還是儲存數據,了解如何使用文件至關重要。幸運的是,Python 的內建函數可讓您輕鬆建立、開啟、讀取、寫入和操作文件,而無需費力。

在本文中,我們將深入探討 Python 中檔案處理的基礎知識,涵蓋從開啟檔案到處理 CSV 和 JSON 等常見檔案格式的所有內容。我們還將分享有關高效處理大文件並確保您安全處理文件的技巧。最後,您將自信地使用 Python 來管理專案中的檔案。

我們將要涵蓋的內容:

  1. 開啟和關閉檔案
  2. 從檔案讀取
  3. 寫入檔案
  4. 處理二進位檔案
  5. 處理異常
  6. 使用 os 和 pathlib 進行檔案操作
  7. 使用 CSV 和 JSON 檔案
  8. 高效文件處理技巧
  9. 文件編碼與跨平台注意事項

1. 開啟和關閉文件

當您使用文件時,第一步是開啟文件。在 Python 中,這是使用 open() 函數完成的,該函數有兩個主要參數:檔案名稱和要開啟檔案的模式(例如讀取“r”、寫入“w”或附加“a”) )。完成後,關閉文件以釋放資源非常重要。

範例:

# Open a file in write mode
file = open("example.txt", "w")

# Write some content to the file
file.write("Hello, World!")

# Always close the file after you're done to free up system resources
file.close()

登入後複製
登入後複製
登入後複製

說明:

open("example.txt", "w"):以寫入模式開啟檔案 example.txt。如果該檔案不存在,Python 將建立它。如果確實存在,則會被覆蓋。
file.write("Hello, World!"):寫入字串「Hello, World!」到檔案。
file.close():關閉文件,這是確保保存所有變更並釋放資源所必需的。
更好的實踐:使用 with 語句

with 語句會在您完成後自動關閉文件,因此您無需明確呼叫 close()。

with open("example.txt", "w") as file:
    file.write("Hello, World!")
# The file is automatically closed here, even if an error occurs
登入後複製
登入後複製
登入後複製

說明:

with 語句確保在執行程式碼區塊後自動關閉文件,即使程式碼區塊內發生錯誤也是如此。這可以防止意外的資料遺失或資源外洩。

2. 從檔案中讀取

Python 中有多種讀取檔案的方法,取決於您是要一次讀取整個檔案還是逐行處理它。

範例(讀取整個檔案):

with open("example.txt", "r") as file:
    content = file.read()  # Read the entire file at once
    print(content)
登入後複製
登入後複製
登入後複製

說明:

open("example.txt", "r"): 以讀取模式開啟檔案 ("r")。
file.read():將檔案的全部內容讀入變數content。這適用於小文件,但對於大文件可能效率低下。
print(content): 將內容輸出到控制台。

範例(高效率逐行閱讀):

# Open a file in write mode
file = open("example.txt", "w")

# Write some content to the file
file.write("Hello, World!")

# Always close the file after you're done to free up system resources
file.close()

登入後複製
登入後複製
登入後複製

說明:

for line in file 循環逐行讀取文件,從而提高大文件的記憶體效率。
line.strip():在列印之前從每行中刪除任何前導/尾隨空格或換行符。

3. 寫入文件

要將資料寫入文件,我們使用「w」或「a」模式。 「w」模式會覆蓋文件,而「a」會追加到現有內容。

範例(寫入檔案):

with open("example.txt", "w") as file:
    file.write("Hello, World!")
# The file is automatically closed here, even if an error occurs
登入後複製
登入後複製
登入後複製

說明:

open("example.txt", "w"):以寫入模式開啟文件,如果文件不存在則建立該文件,如果存在則刪除內容。
file.write():將字串寫入檔案。如果需要,您可以在新行中新增 n。

範例(附加到文件):

with open("example.txt", "r") as file:
    content = file.read()  # Read the entire file at once
    print(content)
登入後複製
登入後複製
登入後複製

說明:

open("example.txt", "a"):以追加模式("a")開啟文件,這表示新資料將新增至文件末尾,而不刪除現有內容。
file.write("nThis will beappend at the end."):在檔案結尾寫入新行,新增 n 移動到新行。

4. 處理二進位文件

處理非文字檔案(例如影像、影片或其他二進位資料)時,需要使用二進位模式(「rb」用於讀取,「wb」用於寫入)。

範例(讀取二進位檔案):

with open("example.txt", "r") as file:
    for line in file:  # Loop through each line in the file
        print(line.strip())  # Remove trailing newline characters and print the line
登入後複製
登入後複製

說明:

open("image.jpg", "rb"):以讀取二進位模式("rb")開啟文件,這對於二進位資料是必需的。
binary_file.read():讀取檔案的整個二進位內容。
binary_data[:10]:顯示檔案的前 10 個位元組。這對於預覽或處理區塊中的二進位資料非常有用。

5. 異常處理

處理檔案時,可能會發生檔案遺失或權限問題等錯誤。您可以使用 try- except 區塊優雅地處理這些錯誤。

範例:

with open("example.txt", "w") as file:
    file.write("Writing a new line of text.")
登入後複製
登入後複製

說明:

try 區塊嘗試開啟並讀取可能不存在的檔案。
如果未找到文件,則 except FileNotFoundError 區塊會捕獲錯誤並列印一條用戶友好的訊息,而不是使程式崩潰。

6.使用os和pathlib進行檔案操作

os 和 pathlib 模組提供了與檔案系統互動的方法,而不僅僅是開啟和關閉檔案。您可以檢查檔案是否存在、重新命名或刪除它們。

範例(作業系統模組):

# Open a file in write mode
file = open("example.txt", "w")

# Write some content to the file
file.write("Hello, World!")

# Always close the file after you're done to free up system resources
file.close()

登入後複製
登入後複製
登入後複製

說明:

with open("example.txt", "w") as file:
    file.write("Hello, World!")
# The file is automatically closed here, even if an error occurs
登入後複製
登入後複製
登入後複製

範例(pathlib 模組):

with open("example.txt", "r") as file:
    content = file.read()  # Read the entire file at once
    print(content)
登入後複製
登入後複製
登入後複製

說明:

Path("new_example.txt"):建立一個指向檔案的 Path 物件。
file_path.exists(): 檢查檔案是否存在。
file_path.unlink(): 刪除檔案。

7. 使用 CSV 和 JSON 文件

Python 的 csv 和 json 模組可以輕鬆處理結構化資料格式,例如 CSV(逗號分隔值)和 JSON(JavaScript 物件表示法)。

CSV 檔案

csv 模組可讓您處理按行和列組織的資料。

範例(寫入 CSV):

with open("example.txt", "r") as file:
    for line in file:  # Loop through each line in the file
        print(line.strip())  # Remove trailing newline characters and print the line
登入後複製
登入後複製

說明:

csv.writer(file):建立一個 writer 物件以將行寫入 CSV 檔案。
writer.writerow():將每一行資料寫入檔案。

範例(讀取 CSV):

with open("example.txt", "w") as file:
    file.write("Writing a new line of text.")
登入後複製
登入後複製

說明:

在上面的程式碼區塊中,csv.reader(file):建立一個迭代 CSV 檔案中每一行的讀取器物件。
讀取器循環中的 for row 讀取每一行並列印它。
JSON 檔案
json 模組非常適合讀取和寫入鍵值對結構的資料。

範例(寫 JSON):

with open("example.txt", "a") as file:
    file.write("\nThis will be appended at the end.")
登入後複製

說明:

json.dump(data, file):將字典資料以 JSON 形式寫入檔案。

範例(讀取 JSON):

with open("image.jpg", "rb") as binary_file:
    binary_data = binary_file.read()  # Read the entire file in binary mode
    print(binary_data[:10])  # Print first 10 bytes for preview
登入後複製

說明:

json.load(file):讀取 JSON 檔案並轉換回 Python 字典。

8.高效率文件處理技巧

處理大型檔案時,分塊處理檔案比將整個檔案載入到記憶體中更有效。

範例(分塊閱讀):

try:
    with open("nonexistentfile.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("The file does not exist!")
登入後複製

結論

在 Python 中處理檔案既簡單又強大。無論您是處理文字檔案、儲存資料還是處理大型資料集,掌握檔案操作都將使您的編碼生活更加輕鬆。透過我們在本文中介紹的提示和技術,您將能夠順利編寫更有效率、可靠且可擴展的 Python 程式。

感謝您的閱讀...

以上是Python 文件處理簡介的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!