2

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'
shasj
  • 85
  • 1
  • 6
  • Sorry for my code. I don´t know write code in this site – shasj Jan 24 '14 at 13:48
  • 1. Remove all the back ticks. 2. All code needs to be indented by at least 4 spaces. – Gerrat Jan 24 '14 at 13:48
  • (1) you can use block code by highlighting the section and clicking the `{}` button. (2) you don't need a new line spacing for each line of code... – alvas Jan 24 '14 at 13:49

1 Answers1

2

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})
Gerrat
  • 28,863
  • 9
  • 73
  • 101
  • Thanks very much! In this syntaxe compress the directory too, but I'd like compress only the file. You know how I do this? Thanks – shasj Jan 24 '14 at 14:09
  • You have directory names that end in `.xlsx`??? If you want only files, you probably want to traverse the directory differently (eg. see answer [here](http://stackoverflow.com/questions/120656/directory-listing-in-python) ) – Gerrat Jan 24 '14 at 19:00