使用循环在python中压缩几个文件

时间:2014-01-24 13:46:23

标签: python loops zip

如何在python中使用一个循环压缩多个文件?

我试过了,但它给了我一个错误:

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

这是追溯:

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'

1 个答案:

答案 0 :(得分:2)

如果您查看Python's string formatting documentation,只要您的字符串包含mapping之类的内容,就会使用'%(name)s类型的操作。为此,您需要使用像dict这样的映射对象来跟踪它,例如:

'%(name)s' % {'name':name}

您需要将此添加到您放置'%(name)s'

的每个位置

所以这些行:

zf = zipfile.ZipFile('%(name)s.zip', mode='w')
zf.write('%(name)s')
print_info('%(name)s')

应写成:

zf = zipfile.ZipFile('%(name)s.zip' % {'name':name}, mode='w')
zf.write('%(name)s' % {'name':name})
print_info('%(name)s' % {'name':name})