Reputation: 85
How can I zip multiple files using one loop in python?
I tried this but It gives me a error:
from zipfile_infolist import print_info
import zipfile
import fileinput
import glob
import os
for name in glob.glob( '*.xlsx' ):
zf = zipfile.ZipFile('%(name)s.zip', mode='w')
try:
zf.write('%(name)s')
finally:
print 'closing'
zf.close()
print
print_info('%(name)s')
This is the traceback:
Traceback (most recent call last):
File "C:/Users/Fatt-DELL-3/ser.py", line 10, in <module>
zf.write('%(name)s')
File "C:\Program Files\IBM\SPSS\Statistics\22\Python\lib\zipfile.py", line 1031, in write
st = os.stat(filename)
WindowsError: [Error 2] The system can not find the file specified: '%(name)s'
Upvotes: 2
Views: 1307
Reputation: 29690
If you have a look at Python's string formatting documentation, you're using a mapping
type of operation whenever your string includes something like '%(name)s
. For that, you need to follow it with a mapping object like a dict, eg:
'%(name)s' % {'name':name}
You need to add this to every place where you've put '%(name)s'
So these lines:
zf = zipfile.ZipFile('%(name)s.zip', mode='w')
zf.write('%(name)s')
print_info('%(name)s')
should be written as:
zf = zipfile.ZipFile('%(name)s.zip' % {'name':name}, mode='w')
zf.write('%(name)s' % {'name':name})
print_info('%(name)s' % {'name':name})
Upvotes: 2