在 Linux 解開 Windows 打包的 zip,中文檔名變成問號或亂碼,是因為編碼不同:Windows 常用 GBK,而 Linux 預設 UTF-8。以下四種方式由簡到繁。
unzip -O CP936 xxx.zip # GBK、GB18030 亦可
有趣的是 unzip 的 manual 並未記載這個參數,只有 unzip --help 簡單提了一行。
在 /etc/environment 加入兩行:
UNZIP="-O CP936" ZIPINFO="-O CP936"
之後所有 unzip 都會以該編碼顯示與解壓。
jar xvf file.zip
Java 的 jar 指令對中文檔名的相容性通常不錯,是快速繞過問題的偏方。
存成 uzip:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# uzip.py
import os
import sys
import zipfile
print "Processing File " + sys.argv[1]
file = zipfile.ZipFile(sys.argv[1], "r")
for name in file.namelist():
utf8name = name.decode('gbk')
print "Extracting " + utf8name
pathname = os.path.dirname(utf8name)
if not os.path.exists(pathname) and pathname != "":
os.makedirs(pathname)
data = file.read(name)
if not os.path.exists(utf8name):
fo = open(utf8name, "w")
fo.write(data)
fo.close
file.close()
加上執行權限後使用:
chmod +x uzip ./uzip xxxx.zip
實務建議:優先試方法一,遇到 unzip 版本不支援 -O 時再用方法二;方法四較適合大量批次處理,但腳本中的編碼需依實際來源改為 utf-8 或 big5。若要在 Python 3 執行,print 需改寫成函式形式。