有一个简单的Python函数可以解压缩.zip文件吗?:
unzip(ZipSource, DestinationDirectory)
Run Code Online (Sandbox Code Playgroud)
我需要解决方案在Windows,Mac和Linux上采取相同的行动:如果zip是文件,则始终生成文件;如果zip是目录,则始终生成目录;如果zip是多个文件,则生成目录; 总是在给定目标目录内,而不是在给定目标目录中
如何在Python中解压缩文件?
phi*_*hag 44
使用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)
Run Code Online (Sandbox Code Playgroud)
请注意,使用extractall会更短,但该方法不能防止Python 2.7.4之前的路径遍历漏洞.如果您可以保证您的代码在最新版本的Python上运行.