【问题标题】:zipping files generated on the fly压缩动态生成的文件
【发布时间】:2015-09-18 00:29:21
【问题描述】:

如何压缩“飞”生成的一堆文件?

我正在用这个小规模的场景进行测试:

from time import strftime
import zipfile

# create new file
today = strftime("%Y-%m-%d %H:%M:%S")

new_file = open('testing123.txt', 'w')
text = 'this file was just added:' + str(today)
new_file.write(text)

# create zip file and write to it
newZip = zipfile.ZipFile("test.zip", "w")
newZip.write('testing123.txt')
new_file.close()

print "file created"

两件事,首先在脚本顶部创建的testing123.txt 在您解压缩创建的 zip 文件时是空白的,这应该包括循环生成的文件列表。

所以我想知道什么是动态生成一堆文件的最佳方法,然后将它们全部压缩到一个 zip 文件夹中。

【问题讨论】:

  • 你应该在开始压缩之前先new_file.close()
  • 你可以打开拉链并继续添加

标签: python python-2.7 zipfile


【解决方案1】:

首先,文件解压后显示为空的原因是您在使用后没有关闭您的文本文件。因为您没有关闭文件,所以您的 write 实际上并没有提交到磁盘,所以 ZipFile.write 看到了一个空文件。您可以使用with 在完成文件后自动关闭文件,因此您永远不必忘记.close

with open('testing123.txt', 'w') as new_file:
    new_file.write('this file was just added:' + str(today))

(您也可以使用.flush() 来强制提交写入,但这不太常见)。

其次,如果您以编程方式生成文件内容,则应使用.writestr 写入字符串,而无需在磁盘上创建实际文件:

newZip = zipfile.ZipFile("test.zip", "w")
newZip.writestr('testing123.txt', 'this file was just added:' + str(today))
newZip.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多