I am hoping someone might point me in the right direction. I am still very newbie with coding and python. I am currently trying to open a zip file and I keep getting "file is not a zip file". I have checked using “file” in terminal and it shows as a zip along with I know the file is created as a zip. I am able to unpack the file with no issue. Any help on how to resolve this is appreciated. In my google searches I haven't come across anything.

import zipfile 

archive_location = <path_to_archive>

f = zipfile.ZipFile(archive_location, 'r')
for filename in f.namelist():
    print 'File', filename


 File "unarchive.py", line 15, in <module>
    f = zipfile.ZipFile(archive_location, 'r')
  File "/usr/lib/python2.6/zipfile.py", line 696, in __init__
    self._GetContents()
  File "/usr/lib/python2.6/zipfile.py", line 716, in _GetContents
    self._RealGetContents()
  File "/usr/lib/python2.6/zipfile.py", line 728, in _RealGetContents
    raise BadZipfile, "File is not a zip file"
zipfile.BadZipfile: File is not a zip file

Recommended Answers

All 4 Replies

I did see this but I think I missed a key piece while bashing my face against the wall. So python says it is not a zip file which would make sense on why it would be a badzip file. Not sure how to get to the bottom of it. My overall goal is to grab a file from inside the archive would it be better to just extract it using a system command?

I should mention I will be doing this for a large amount of files.

Did you try the infolist method like vegaseat? This works for me:

# Code part adapted from vegaseat    21jan2007 codesnippet

import zipfile
zfilename = r'I:/Lataukset/15Puzzle.zip'
# open the zipped file
zfile = zipfile.ZipFile( zfilename, "r" )

# retrieve information about the zip file
zfile.printdir()

print '-'*40

# get each archived file and process the decompressed data
for info in zfile.infolist():
    fname = info.filename
    # decompress each file's data
    data = zfile.read(fname)

    # testing --> display file's contents if a text or python file
    if fname.endswith((".txt",'.py')):
        print '-'*40
        print "This is the contents of %s:" % fname
        print '-'*40
        print data

I don't get that far, If i do

zfile = zipfile.ZipFile( zfilename, "r" )

It bombs out saying it is a badzipfile. considering linux says it is a zip and python says it is not a zip what would be the best way to handle this? would it be better to use a os.system(7zip) to unpack the file and do what needs to be done?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.