2

I'm trying to zip up only *.csv files in a directory with this code:

allFiles = os.listdir( dirName + apt + '/' )
csvList  = [i for i in allFiles if i.endswith('.csv')]
zf       = zipfile.ZipFile([ dirName + apt + '.zip' ], mode='w')
for f in csvList:
    a    = dirName + apt + '/' + f
    zf.write( a )
#all the elements of a are strings

I get the error:

Traceback (most recent call last):
File "<ipython-input-43-ebf4dc807b56>", line 1, in <module>
zf.write(a)
File "C:\Users\blevy\MCR\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\zipfile.py", line 1347, in write
zinfo.header_offset = self.fp.tell()    # Start of header bytes

AttributeError: 'list' object has no attribute 'tell'

Is there a simple fix to this error?

Mel
  • 5,837
  • 10
  • 37
  • 42
Benjamin Levy
  • 333
  • 6
  • 19

1 Answers1

5

This line:

zf = zipfile.ZipFile([ dirName + apt + '.zip' ], mode='w')

should be:

zf = zipfile.ZipFile(dirName + apt + '.zip', mode='w')

This is because ZipFile takes a file name, not a list of file names.

Thanos
  • 2,472
  • 1
  • 16
  • 33
Gerrat
  • 28,863
  • 9
  • 73
  • 101
  • The contents of dirName + apt + '.zip' form a string. The string, dirName', has the '/' characters, but this is a Windows machine that I'm using. Hope that helps clarify. – Benjamin Levy May 25 '16 at 22:23
  • @BenjaminLevy: Doesn't help. You have `[` and `]` around your file name. That makes it a list. `ZipFile` doensn't take a list - it takes a single file name. You need to remove the brackets. – Gerrat May 25 '16 at 22:27
  • Well, duh on me. I'll try it and write back. Tx. – Benjamin Levy May 25 '16 at 22:42
  • Thanks, Gerrat. Your advice worked. My matlab training of using [ str + str] to concatenate strings tripped me up. I could not see the error in Python. – Benjamin Levy May 26 '16 at 13:18
  • that looks like a stupid typo but it happened to me when passing a list instead of the list first element... googling the error message landed here. Thanks – Jean-François Fabre Jul 21 '21 at 19:56