簡體   English   中英

python 2.7 Mass zip文件提取到目標目錄

[英]python 2.7 mass zip file extraction to target directory

我正在嘗試遍歷壓縮文件的文件夾並將其提取到目標目錄。 我的代碼是:

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

任何想法有什么問題嗎?

嘗試將zipfile.extract更改為zip_file.extractall

編輯:從手機回來,這里是一些更干凈的代碼。 我注意到初始代碼無法按原樣運行,因為“文件名”實際上是該目錄的文件列表。 此外,打開它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)

是我前一段時間使用的zipfile代碼示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM