在 Python 中,我們可以透過 os 模組來操作檔案,例如:
- 建立檔案
- 刪除檔案
- 修改檔名
📦 匯入模組
import os
📄 建立檔案(新增檔案)
🔹 建立空白檔案
file_path = 'path/to/file.txt'open(file_path, 'w').close()
👉 如果檔案不存在,會自動建立
👉 如果已存在,內容會被清空(⚠️ 注意)
🔹 建立並寫入內容
file_path = 'path/to/file.txt'with open(file_path, 'w') as file: file.write('這是檔案的內容。')
👉 建議使用 with,會自動關閉檔案
🗑️ 刪除檔案
file_path = 'path/to/file.txt'os.remove(file_path)
👉 直接刪除檔案(不可復原,請小心)
✏️ 更改檔案名稱(重新命名)
old_file_path = 'path/to/old_file.txt'new_file_path = 'path/to/new_file.txt'os.rename(old_file_path, new_file_path)
👉 可以用來:
- 改檔名
- 移動檔案(如果路徑不同)
⚠️ 常見錯誤與建議
1️⃣ 檔案不存在會報錯
os.remove(file_path)
👉 建議先檢查:
if os.path.exists(file_path): os.remove(file_path)
2️⃣ 避免覆蓋檔案
if not os.path.exists(file_path): with open(file_path, 'w') as file: file.write('內容')
3️⃣ 路徑寫法注意
- Windows:
C:/Users/...或C:\\Users\\... - 建議用:
os.path.join('path', 'to', 'file.txt')
🎯 小結
透過這些方法,你可以做到:
✔ 建立檔案
✔ 寫入內容 ✔ 刪除檔案 ✔ 修改檔名



















