Last active
February 13, 2026 04:36
-
-
Save kujirahand/3e6e50f485dc5cbaef996bb589a89d95 to your computer and use it in GitHub Desktop.
ZIPファイル内の日本語ファイル名を復元して再圧縮するツール
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ZIPファイルの中身を検査するスクリプト""" | |
| import sys | |
| import zipfile | |
| def main(path_input_zip): | |
| """メイン処理""" | |
| # 出力ファイル名を決定 --- (※1) | |
| path_output_zip = path_input_zip + ".fixed.zip" | |
| with zipfile.ZipFile(path_input_zip, 'r') as zin: | |
| with zipfile.ZipFile(path_output_zip, 'w', zipfile.ZIP_DEFLATED) as zout: | |
| # ZIPファイルを一つずつ処理 --- (※2) | |
| for item in zin.infolist(): | |
| # ZIPファイル内のファイル名を復元 --- (※3) | |
| fname = decode_zip_filename(item.filename) | |
| # macOSのメタデータを無視 --- (※4) | |
| if fname.startswith("__MACOSX/") or fname.endswith(".DS_Store"): | |
| print("❌無視: " + fname) | |
| continue | |
| # ファイルを読み込んでそのまま書き出す --- (※5) | |
| data = zin.read(item.filename) | |
| print("🎁追加: " + fname) | |
| zout.writestr(fname, data) # ファイル名を指定して圧縮 | |
| print(f"検査して出力しました: {path_output_zip}") | |
| def decode_zip_filename(name: str) -> str: | |
| """いろいろなエンコーディングを試してファイル名を復元する""" # --- (※6) | |
| try: | |
| # デフォルトでPythonはcp437として解釈 | |
| raw = name.encode("cp437") | |
| except UnicodeEncodeError: | |
| return name | |
| # まずよくある文字コードを試し、最後はcp437をそのまま採用 | |
| for encoding in ("utf-8", "cp932"): | |
| try: | |
| return raw.decode(encoding) | |
| except UnicodeDecodeError: | |
| continue | |
| return raw.decode("cp437") | |
| if __name__ == "__main__": | |
| if len(sys.argv) < 2: | |
| print("Usage: python check.py <zipfile>") | |
| sys.exit(1) | |
| main(sys.argv[1]) | |
| sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment