python - 使用循环在Python中压缩多个文件

标签 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'

最佳答案

如果您查看Python's string formatting documentation ,每当您的字符串包含诸如 '%(name)s 之类的内容时,您就在使用 mapping 类型的操作。为此,您需要在其后面添加一个映射对象(例如字典),例如:

'%(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})

关于python - 使用循环在Python中压缩多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21334328/

相关文章:

jQuery ajax 调用 httphandler 返回 zip 文件

python - 比较两个字符串中是否存在元音的函数

Python scrapy reddit 确认按钮中断抓取

Java while 循环处理 netbean 错误

python - 为什么我的 "if"语句在使用 "break"函数时没有退出?

python - 在 Python 中将类文件对象添加到 Zip 文件

python - 内存 Zip 文件中的 Python 错误

python - Travis CI 和 pytest 具有多个 python 版本

python - PySchools - 主题 1 问题 7

PHP 数组在 foreach() 中获取下一个键/值