在 Python 中解压文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3451111/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:08:50  来源:igfitidea点击:

Unzipping files in Python

pythonzipunzipzipfile

提问by John Howard

I read through the zipfiledocumentation, but couldn't understand how to unzipa file, only how to zip a file. How do I unzip all the contents of a zip file into the same directory?

我通读了zipfile文档,但无法理解如何解压缩文件,只能理解如何压缩文件。如何将 zip 文件的所有内容解压缩到同一目录中?

采纳答案by Rahul

import zipfile
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
    zip_ref.extractall(directory_to_extract_to)

That's pretty much it!

差不多就是这样!

回答by Dan Breen

Use the extractallmethod, if you're using Python 2.6+

使用该extractall方法,如果您使用的是 Python 2.6+

zip = ZipFile('file.zip')
zip.extractall()

回答by user1741137

If you are using Python 3.2or later:

如果您使用的是Python 3.2或更高版本:

import zipfile
with zipfile.ZipFile("file.zip","r") as zip_ref:
    zip_ref.extractall("targetdir")

You dont need to use the closeor try/catchwith this as it uses the context managerconstruction.

您不需要使用closetry/catch,因为它使用 上下文管理器构造。

回答by user3911901

import os 
zip_file_path = "C:\AA\BB"
file_list = os.listdir(path)
abs_path = []
for a in file_list:
    x = zip_file_path+'\'+a
    print x
    abs_path.append(x)
for f in abs_path:
    zip=zipfile.ZipFile(f)
    zip.extractall(zip_file_path)

This does not contain validation for the file if its not zip. If the folder contains non .zip file it will fail.

如果文件不是 zip,这不包含对文件的验证。如果文件夹包含非 .zip 文件,它将失败。

回答by simhumileco

You can also import only ZipFile:

您也可以只导入ZipFile

from zipfile import ZipFile
zf = ZipFile('path_to_file/file.zip', 'r')
zf.extractall('path_to_extract_folder')
zf.close()

Works in Python 2and Python 3.

适用于Python 2Python 3

回答by Done Jin

try this :

尝试这个 :


import zipfile
def un_zipFiles(path):
    files=os.listdir(path)
    for file in files:
        if file.endswith('.zip'):
            filePath=path+'/'+file
            zip_file = zipfile.ZipFile(filePath)
            for names in zip_file.namelist():
                zip_file.extract(names,path)
            zip_file.close() 

path : unzip file's path

path : 解压文件的路径