Photo by Aaron Burden on Unsplash 在實務上,常常有機會需要將資料寫入或讀出檔案,而 Python 也提供了許多相關的模組 (Module) 讓開發人員可以容易的進行檔案的操作。 透過本篇的教學,各位除了能夠利用 Python 進行基本的檔案操作外,也有能力讀取及寫入常見的資料交換格式檔案,重點包含: 基本的檔案操作 JSON 檔案操作 (JSON Files) CSV 檔案操作 (CSV Files) ZIP 檔案操作 (Zip Files) 一、基本的檔案操作 首先,先來看一下我們目前專案的檔案結構,如下: 現在就來分別介紹幾個 Python 常用的檔案操作方式: 檢查檔案是否存在 利用 Path 模組 (Module) 中的 exists() 方法, 來檢查目錄下是否含有特定的檔案,如下範例: from pathlib import Path file = Path("blog/about.py") print(file.exists()) #執行結果:True 取得檔案資訊 利用 Path 模組 (Module) 中的 stat() 方法即可取得目錄下特定檔案的資訊,如下範例: from pathlib import Path file = Path("blog/about.py") print(file.stat()) 執行結果 從執行結果可以看到包含了檔案的大小 st_size 、修改時間 st_mtime 及建立時間 st_ctime 等。 重新命名檔案 利用 Path 模組 (Module) 中的 rename() 方法,並且傳入新的檔案名稱及路徑即可實現檔案重新命名的動作,如下範例: from pathlib import Path file = Path("blog/about.py") file.rename("blog/info.py") 寫入檔案資料 利用 Path 模組 (Module) 中的 write_text() 方法,並且傳入要寫入的資料。 ...