使用Python2.7.5将文件夹中的所有压缩文件解压缩到同一文件夹

2024-04-28 04:05:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想编写一个简单的脚本来遍历文件夹中的所有文件,并将压缩文件(.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)

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

我想在我看来,这个过程应该是这样的:

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

不过,谢谢马库斯,在执行建议时,我又出现了一个错误:

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]]])

Open a ZIP file, where file can be either a path to a file (a string) or a file-like object

在我看来,一切都是存在和解释的。我只是不明白我做错了什么。

有什么建议吗?

谢谢你


Tags: 文件in文件夹osextractzipitemtools
3条回答
接受的答案太好了!

为了扩展这个想法,在一个目录中的所有子目录中解压所有扩展名为.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()

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

    zipfile.ZipFile.extract(item)

是错误的。

    zipfile.ZipFile(item).extractall()

将从zip文件中提取名称包含在item中的所有文件。

我认为您应该更仔细地阅读文档以zipfile:)但是您走的是正确的道路!

下面是对我有用的代码:

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

相关问题 更多 >