如何在所有操作系统上用 Python 解压缩文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12886768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to unzip file in Python on all OSes?
提问by tkbx
Is there a simple Python function that would allow unzipping a .zip file like so?:
是否有一个简单的 Python 函数可以像这样解压缩 .zip 文件?:
unzip(ZipSource, DestinationDirectory)
I need the solution to act the same on Windows, Mac and Linux: always produce a file if the zip is a file, directory if the zip is a directory, and directory if the zip is multiple files; always inside, not at, the given destination directory
我需要在 Windows、Mac 和 Linux 上执行相同操作的解决方案:如果 zip 是文件,则始终生成文件,如果 zip 是目录,则始终生成目录,如果 zip 是多个文件,则生成目录;总是在给定的目标目录中,而不是在
How do I unzip a file in Python?
如何在 Python 中解压缩文件?
采纳答案by phihag
Use the zipfilemodule in the standard library:
使用zipfile标准库中的模块:
import zipfile,os.path
def unzip(source_filename, dest_dir):
with zipfile.ZipFile(source_filename) as zf:
for member in zf.infolist():
# Path traversal defense copied from
# http://hg.python.org/cpython/file/tip/Lib/http/server.py#l789
words = member.filename.split('/')
path = dest_dir
for word in words[:-1]:
while True:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if not drive:
break
if word in (os.curdir, os.pardir, ''):
continue
path = os.path.join(path, word)
zf.extract(member, path)
Note that using extractallwould be a lot shorter, but that method does notprotect against path traversal vulnerabilitiesbefore Python 2.7.4. If you can guarantee that your code runs on recent versions of Python.
请注意, usingextractall会更短,但该方法不能防止Python 2.7.4 之前的路径遍历漏洞。如果你能保证你的代码在最新版本的 Python 上运行。
回答by Dave
Python 3.x use -e argument, not -h.. such as:
Python 3.x 使用 -e 参数,而不是 -h .. 例如:
python -m zipfile -e compressedfile.zip c:\output_folder
arguments are as follows..
论据如下..
zipfile.py -l zipfile.zip # Show listing of a zipfile
zipfile.py -t zipfile.zip # Test if a zipfile is valid
zipfile.py -e zipfile.zip target # Extract zipfile into target dir
zipfile.py -c zipfile.zip src ... # Create zipfile from sources

