Windows 下使用 os.listdir()、os.path.abspath() 讀取中文目錄時,路徑出現亂碼(如 һɳ),導致 open() 失敗。
Python 3 預設使用 UTF-8,但 Windows 檔案系統 API 回傳的是系統預設編碼(通常為 GBK/CP936)。若直接將位元組串解碼為 UTF-8 即產生亂碼。
Path 物件自動處理編碼轉換。
from pathlib import Path
for p in Path(input_dir).iterdir():
print(p) # 正確顯示中文
os.listdir() 後以 sys.getfilesystemencoding() 解碼。
import os, sys
fs_enc = sys.getfilesystemencoding() # 'mbcs' 或 'gbk'
names = os.listdir(input_dir)
for n in names:
true_name = n.encode(fs_enc).decode('utf-8') # 若需統一為 utf-8
sys.setdefaultencoding:此函數在 Python 3 已移除,強行修改會破壞內部一致性。全程使用 pathlib.Path 或 os.scandir()(回傳 DirEntry 含正確字串),並在開啟檔案時直接傳入 Path 物件,讓底層處理編碼。