Search code examples
pythonpython-2.xzip

Python doesn't recognize zip files as zip files


I iterate through the directories and want to find all zip files and add them to download_all.zip I am sure there are zip files, but Python doesn't recognize those zip files as zip files. Why is that?

my code:

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

I tried:

file.printdir()
# I got the following error: AttributeError: 'str' object has no attribute 'printdir'

Solution

  • zipfile.Zipfile.write(name), name actually stands for full file path, not just filename.

    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) # no error