zipfileの圧縮と解凍

5033 ワード

zipfileはpythonが提供する内蔵の圧縮方法です
zipファイルを圧縮および解凍できます
圧縮:
 zf = ZipFile("out.zip", "w", mode=zipfile.ZIP_STORED)
zf.write(「ファイルフルパス」,「アーカイブフルパス(つまり圧縮パッケージに書き込まれる相対パス)」
説明:
zipfile.ZIP_STOREDはデフォルトの圧縮方式で、実はただ記憶して、内容の圧縮を行いません
圧縮を使用するには、import zlibライブラリが必要です.
次のようになります.
import zipfile
try:
    import zlib
    mode= zipfile.ZIP_DEFLATED
except:
    mode= zipfile.ZIP_STORED

zip= zipfile.ZipFile('zipfilename', 'w', mode)
zip.write(item)
zip.close()

公式ドキュメントを参照してください.zipfile. ZIP_STORED
The numeric constant for an uncompressed archive member. zipfile. ZIP_DEFLATED
The numeric constant for the usual ZIP compression method. This requires the zlib module. No other compression methods are currently supported.
圧縮してファイルが大きくなったのも無理はない
しかしzipfile用のデフォルト圧縮アルゴリズムはzlibであり、現在はこれのみがサポートされている.
解凍:
解凍は簡単ですZipFile. extract
(
member
[,
path
[,
pwd
]
]
)
Extract a member from the archive to the current working directory; member must be its full name or a ZipInfo object). Its file information is extracted as accurately as possible. path specifies a different directory to extract to. member can be a filename or a ZipInfo object. pwd is the password used for encrypted files.
Returns the normalized path created (a directory or new file).
New in version 2.6.
Note
If a member filename is an absolute path, a drive/UNC sharepoint and leading (back)slashes will be stripped, e.g.: ///foo/bar becomes foo/bar on Unix, and C:\foo\bar becomes foo\bar on Windows. And all ".." components in a member filename will be removed, e.g.: ../../foo../../ba..r becomes foo../ba..r . On Windows illegal characters ( : , < , > , | , " , ? , and * ) replaced by underscore ( _ ). ZipFile. extractall
(
[
path
[,
members
[,
pwd
]
]
]
)
Extract all members from the archive to the current working directory. path specifies a different directory to extract to. members is optional and must be a subset of the list returned by namelist() . pwd is the password used for encrypted files.
文書を読む能力がまだ足りないことを説明しました!強化します!!!