使用Python 2.7.5将一个文件夹中的所有压缩文件解压缩到同一文件夹中

问题描述 投票:9回答:4

我想编写一个简单的脚本来遍历文件夹中的所有文件,然后将压缩后的文件(.zip)解压缩到同一文件夹。对于这个项目,我有一个包含将近100个压缩的.las文件的文件夹,我希望找到一种简单的方法来批量解压缩它们。我尝试使用以下脚本

import os, zipfile

folder = 'D:/GISData/LiDAR/SomeFolder'
extension = ".zip"

for item in os.listdir(folder):
    if item.endswith(extension):
        zipfile.ZipFile.extract(item)

但是,当我运行脚本时,出现以下错误:

Traceback (most recent call last):
  File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 10, in <module>
    extract = zipfile.ZipFile.extract(item)
TypeError: unbound method extract() must be called with ZipFile instance as first argument (got str instance instead)

我正在使用python 2.7.5解释器。我查看了zipfile模块(https://docs.python.org/2/library/zipfile.html#module-zipfile)的文档,我想了解我做错了什么。

我想我该过程将如下所示:

  1. 获取文件夹名称
  2. 循环浏览文件夹并找到zip文件
  3. 将压缩文件提取到文件夹中

但是,感谢Marcus,在实施建议时,出现另一个错误:

Traceback (most recent call last):
  File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 12, in <module>
    zipfile.ZipFile(item).extract()
  File "C:\Python27\ArcGIS10.2\lib\zipfile.py", line 752, in __init__
    self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'JeffCity_0752.las.zip'

使用打印语句时,我可以看到文件在其中。例如:

for item in os.listdir(folder):
    if item.endswith(extension):
        print os.path.abspath(item)
        filename = os.path.basename(item)
        print filename

产量:

D:\GISData\Tools\MO_Tools\JeffCity_0752.las.zip
JeffCity_0752.las.zip
D:\GISData\Tools\MO_Tools\JeffCity_0753.las.zip
JeffCity_0753.las.zip

据我了解的文档,

zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])

打开一个ZIP文件,其中文件可以是文件的路径(字符串)或类似文件的对象

在我看来,一切都存在并得到解释。我只是不明白我在做什么错。

有什么建议吗?

谢谢

python python-2.7 unzip zipfile arcpy
4个回答
22
投票

下面是对我有用的代码:

import os, zipfile

dir_name = 'C:\\SomeDirectory'
extension = ".zip"

os.chdir(dir_name) # change directory from working dir to dir with files

for item in os.listdir(dir_name): # loop through items in dir
    if item.endswith(extension): # check for ".zip" extension
        file_name = os.path.abspath(item) # get full path of files
        zip_ref = zipfile.ZipFile(file_name) # create zipfile object
        zip_ref.extractall(dir_name) # extract file to dir
        zip_ref.close() # close file
        os.remove(file_name) # delete zipped file

回想一下我修改的代码,该目录与脚本目录混淆了。

以下内容也可以在不破坏工作目录的情况下起作用。首先删除行

os.chdir(dir_name) # change directory from working dir to dir with files

然后将文件名分配为

file_name = dir_name + "/" + item

4
投票

您需要使用文件名构造一个ZipFile对象,然后然后提取它:

    zipfile.ZipFile.extract(item)

错了。

    zipfile.ZipFile(item).extractall()

将从具有item中名称的zip文件中提取所有文件。

我认为您应该更仔细地阅读zipfile的文档:),但您的方向正确!


4
投票

接受的答案很好!

只是扩展了将目录中所有子目录中具有.zip扩展名的所有文件解压缩的想法,以下代码似乎很好用:

import os
import zipfile

for path, dir_list, file_list in os.walk(dir_path):
    for file_name in file_list:
        if file_name.endswith(".zip"):
            abs_file_path = os.path.join(path, file_name)

            # The following three lines of code are only useful if 
            # a. the zip file is to unzipped in it's parent folder and 
            # b. inside the folder of the same name as the file

            parent_path = os.path.split(abs_file_path)[0]
            output_folder_name = os.path.splitext(abs_file_path)[0]
            output_path = os.path.join(parent_path, output_folder_name)

            zip_obj = zipfile.ZipFile(abs_file_path, 'r')
            zip_obj.extractall(output_path)
            zip_obj.close()

2
投票

我认为这比较短,对我来说很好用。首先导入所需的模块:

import zipfile, os

然后,我定义工作目录:

working_directory = 'my_directory'
os.chdir(working_directory)

之后,您可以组合使用oszipfile到达所需位置:

for file in os.listdir(working_directory):   # get the list of files
    if zipfile.is_zipfile(file): # if it is a zipfile, extract it
        with zipfile.ZipFile(file) as item: # treat the file as a zip
           item.extractall()  # extract it in the working directory
© www.soinside.com 2019 - 2024. All rights reserved.