简体   繁体   中英

Python 3.5 not opening a zip file

I'm not able to open the file downloaded from this URL using Python's zipfile facility.

This file does open using my Mac's built-in deflater, however, and python-magic (via import magic; magic.from_file("...") ) reports that the file is:

'Zip archive data, at least v2.0 to extract' .

Yet when I do:

with open("498200/Broadband Data Dig - Datasets/NYC Connected Broadband Data Dig Files.zip") as fp:
    zipcontent = zipfile.ZipFile(fp)

I get:

BadZipFile: File is not a zip file

My Python version is 3.5.2 . What's going on here?

zipfile.ZipFile claims compatibility with file-like objects , but it almost certainly requires that they be binary mode, not text mode.

For a minimal changes fix, try:

with open("498200/Broadband Data Dig - Datasets/NYC Connected Broadband Data Dig Files.zip",
          "rb") as fp:
    zipcontent = zipfile.ZipFile(fp)

Or as Trey mentioned, just use the with statement on zipfile.ZipFile('name/of/file.zip') directly, without opening it as a plain file first.

ZipFile opens the file based on the file name:

with zipfile.ZipFile("498200/Broadband Data Dig - Datasets/NYC Connected Broadband Data Dig Files.zip") as zip_file:
    print("do stuff with", zip_file)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM