有没有一个简单的Python函数可以像这样解压.zip文件?:
unzip(ZipSource, DestinationDirectory)我需要在Windows、Mac和Linux上执行相同操作的解决方案:如果zip是文件,则始终生成文件;如果zip是目录,则始终生成目录;如果zip是多个文件,则始终生成目录;始终在给定的目标目录中,而不是在给定的目标目录中
如何在Python中解压文件?
发布于 2012-10-15 05:42:59
使用标准库中的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)请注意,使用extractall会短得多,但在Python2.7.4之前,该方法不能对path traversal vulnerabilities进行保护。如果你能保证你的代码可以在最新版本的Python上运行。
发布于 2014-10-23 22:31:23
Python3.x使用-e参数,而不是-h。例如:
python -m zipfile -e compressedfile.zip c:\output_folder参数如下..
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 sourceshttps://stackoverflow.com/questions/12886768
复制相似问题