REdim.Learning
REdim.Learning

Reputation: 645

Can't import python library 'zipfile'

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

Upvotes: 8

Views: 28278

Answers (2)

Ammad
Ammad

Reputation: 4235

Easiest way to zip a file using Python:

import zipfile

zf = zipfile.ZipFile("targetZipFileName.zip",'w', compression=zipfile.ZIP_DEFLATED)
zf.write("FileTobeZipped.txt")
zf.close()

Upvotes: 4

Jean-François Fabre
Jean-François Fabre

Reputation: 140276

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.

Upvotes: 9

Related Questions