尝试从压缩文件中提取文件夹时出错(Python 2.7)

时间:2015-11-15 03:40:50

标签: python zipfile

我正在尝试仅提取名为' 1'的特定文件夹。从保存在文件夹中的每个压缩文件。此文件夹(' 1')还包含其他文件夹和csv文件。

当提取开始时,会创建其他文件夹,但是,我收到此错误,我无法解决它: -

zipfile.BadZipfile:目录中的文件名" 1 / abc / xyz.csv"和标题" 1 \ abc \ xyz.csv"不同

我见过其他类似的查询尝试使用os.path.join来解决路径,但使用zipfile时这同样不起作用

# Import relevant modules
import zipfile
import os

# Path where the zipped files are
zipped_folder_path = "C:/path/folder_containing_zip_files/"

# pick up 1 zip file at a time form the folder to work with
for zfile in os.listdir(zipped_folder_path):

    # Initialialize the input zipfile to read mode
    zip_in = zipfile.ZipFile (zipped_folder_path + zfile, 'r')

    # Find the new folder name as string - from the reverse -> -4 = '.zip' removed
    folder_name = (zipped_folder_path + zfile)[-12:-4]
    print folder_name

    # Make the destination directory - check if it exists before that
    directory = 'C:/path/destination/'
    if not os.path.exists(directory):
        os.makedirs(directory)

    # Work with all folders & files in the ziparchive 1 by 1
    for item in zip_in.infolist():

        # If the folder name is '1' - extract it with folder name. 
        # Donot extract other files / folders
        if (item.filename[0:2] == '1/'):
            zip_in.extract(item, directory + folder_name)


# close the zip archives when done

zip_in.close()

0 个答案:

没有答案