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'
3
  • Sorry for my code. I don´t know write code in this site Commented Jan 24, 2014 at 13:48
  • 1. Remove all the back ticks. 2. All code needs to be indented by at least 4 spaces. Commented Jan 24, 2014 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... Commented Jan 24, 2014 at 13:49

1 Answer 1

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})
Sign up to request clarification or add additional context in comments.

2 Comments

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
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 )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.