Python无法将zip文件识别为zip文件

问题描述 投票:-1回答:4

我遍历目录,想找到所有zip文件,并将它们添加到download_all.zip我确定有zip文件,但是Python无法将这些zip文件识别为zip文件。为什么会这样?

我的代码:

os.chdir(boardpath)
# zf = zipfile.ZipFile('download_all.zip', mode='w')
z = zipfile.ZipFile('download_all.zip', 'w') #creating zip download_all.zip file

for path, dirs, files in os.walk(boardpath):
    for file in files:
        print file
        if file.endswith('.zip'): # find all zip files
                print ('adding', file)
                z.write(file) # error shows: doesn't file is a str object, not a zip file

z.close()
z = zipfile.ZipFile("download_all.zip")
z.printdir()

我尝试过:

file.printdir()
# I got the following error: AttributeError: 'str' object has no attribute 'printdir'
python python-2.x zipfile
4个回答
1
投票

zipfile.Zipfile.write(name),名称实际上代表完整的文件路径,而不仅仅是文件名。

import os #at the top

 if file.endswith('.zip'): # find all zip files  
    filepath = os.path.join(path, file)
    print ('adding', filepath) 
    z.write(filepath) # error

0
投票

files产生的os/walk()是文件名列表。这些文件名只是strings(没有printdir()方法)。


0
投票

ZipFile.write's doc中所述,filename参数必须相对于存档根目录。因此,以下行:

z.write(file)

应该是:

z.write(os.path.relpath(os.path.join(path, file)))

0
投票

您想在打开zip文件存档并为找到的每个文件写入文件时使用上下文管理,因此请使用with。另外,由于要遍历目录结构,因此需要完全限定每个文件的路径。

import os 
import Zipfile
with zipfile.ZipFile('download_all.zip', 'w') as zf:
    for path, dirs, files in os.walk('/some_path'):
        for file in files:
            if file.endswith('.zip'):
                zf.write(os.path.join(path, file))
© www.soinside.com 2019 - 2024. All rights reserved.