Linux 下 unzip 預設使用 UTF-8 解碼檔名,若壓縮包在 Windows (GBK/CP936) 建立,解壓後中文檔名會變亂碼。提供四種實用修正法:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, zipfile
zf = zipfile.ZipFile(sys.argv[1], 'r')
for name in zf.namelist():
utf8name = name.decode('gbk')
print(f"Extracting {utf8name}")
dirname = os.path.dirname(utf8name)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
data = zf.read(name)
if not os.path.exists(utf8name):
with open(utf8name, 'wb') as f:
f.write(data)
zf.close()
用法:chmod +x uzip.py && ./uzip.py xxx.zip
unzip -O CP936 xxx.zip(GBK、GB18030 同理)。man unzip 未記載,但 unzip --help 可見說明。
編輯 /etc/environment 加入:
UNZIP="-O CP936"
ZIPINFO="-O CP936"
重新登入後所有 unzip/zipinfo 自動套用。
jar xvf file.zip(JDK 內建,預設支援 UTF-8,若壓縮包為 UTF-8 可直接用)。
建議:方法二最輕量,方法三適合長期環境,方法一適合無法安裝新版 unzip 的舊系統。