Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't import python library 'zipfile'

Tags:

zip

python-2.7

Feel like a dunce. I'm trying to interact with a zip file and can't seem to use the zipfile library. Fairly new to python

from zipfile import *
#set filename
fpath = '{}_{}_{}.zip'.format(strDate, day, week)

#use zipfile to get info about ftp file
zip = zipfile.Zipfile(fpath, mode='r')
# doesn't matter if I use     
#zip = zipfile.Zipfile(fpath, mode='w')
#or zip = zipfile.Zipfile(fpath, 'wb')

I'm getting this error

zip = zipfile.Zipfile(fpath, mode='r')

NameError: name 'zipfile' is not defined

if I just use import zipfile I get this error:

TypeError: 'module' object is not callable

like image 372
REdim.Learning Avatar asked Dec 12 '16 13:12

REdim.Learning


People also ask

How do I import a ZIP file module in Python?

If you want to import modules and packages from a ZIP file, then you just need the file to appear in Python's module search path. The module search path is a list of directories and ZIP files. It lives in sys. path .

What is ZIP file ZIP file in Python?

The ZIP file format is a common archive and compression standard. This module provides tools to create, read, write, append, and list a ZIP file. Any advanced use of this module will require an understanding of the format, as defined in PKZIP Application Note.

Can we read ZIP files in Python?

Python can work directly with data in ZIP files. You can look at the list of items in the directory and work with the data files themselves.


1 Answers

Two ways to fix it:

1) use from, and in that case drop the zipfile namespace:

from zipfile import *
#set filename
fpath = '{}_{}_{}.zip'.format(strDate, day, week)

#use zipfile to get info about ftp file
zip = ZipFile(fpath, mode='r')

2) use direct import, and in that case use full path like you did:

import zipfile
#set filename
fpath = '{}_{}_{}.zip'.format(strDate, day, week)

#use zipfile to get info about ftp file
zip = zipfile.ZipFile(fpath, mode='r')

and there's a sneaky typo in your code: Zipfile should be ZipFile (capital F, so I feel slightly bad for answering...

So the lesson learnt is:

  • avoid from x import y because editors have a harder time to complete words
  • with a proper import zipfile and an editor which proposes completion, you would never have had this problem in the first place.
like image 183
Jean-François Fabre Avatar answered Sep 19 '22 20:09

Jean-François Fabre