python 2.7质量zip文件提取到目标目录

时间:2016-02-16 17:32:48

标签: python zipfile os.walk

我试图遍历压缩文件的文件夹并将其解压缩到目标目录。我的代码是:

import os
import zipfile

def mass_extract():
    source_directory = raw_input("Where are the zips? ")

    if not os.path.exists(source_directory):
        print "Sorry, that folder doesn't seem to exist."
        source_directory = raw_input("Where are the zips? ")

    target_directory = raw_input("To where do you want to extract the files? ")
    if not os.path.exists(target_directory):
        os.mkdir(target_directory)

    for path, directory, filename in os.walk(source_directory):
        zip_file = zipfile.ZipFile(filename, 'w')
        zipfile.extract(zip_file, target_directory)
        zip_file.close()

    print "Done."

我在这里遇到两个错误:

AttributeError: 'module' object has no attribute 'extract'
Exception AttributeError:"'list' object has no attribute 'tell'" in <bound method ZipFile.__del__ of <zipfile.ZipFile object at 0xb701d52c>> ignored

任何想法有什么不对?

1 个答案:

答案 0 :(得分:3)

尝试将zipfile.extract更改为zip_file.extractall

编辑:从移动设备返回,这里有一些更干净的代码。我注意到初始代码不会按原样运行,因为'filename'实际上是该目录的文件列表。此外,将其打开为write又名w只会覆盖您现有的zip文件,您不希望这样。

for path, directory, filenames in os.walk(source_directory):
    for each_file in filenames:
        file_path = os.path.join(path, each_file)
        if os.path.splitext(file_path)[1] == ".zip": # Make sure it's a zip file
            with zipfile.ZipFile(file_path) as zip_file:
                zip_file.extractall(path=target_directory)

Here是我之前做过的zipfile代码示例。