python - 即时生成的压缩文件

标签 python python-2.7 zip

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

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

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"

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

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

最佳答案

首先,解压后文件显示为空的原因是您在使用后没有关闭文本文件。由于您没有关闭该文件,因此您的 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()

关于python - 即时生成的压缩文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32642043/

相关文章:

python - 获取上一行的值并计算新列 pandas python

python - 杀死Python中的输入

powershell - 压缩归档并保留相对路径

python - 有效地将 CSV 列解压到单独的列表中

windows - 如何在批处理文件 (windows) 中压缩和复制每天创建的文件。

Python 和 MySQL - 非 GCC 模块?

python - Mac OSX 10.5.8 上适用于 Django 的 mod_wsgi

python-2.7 - python 2.7 : Area opening and closing binary image in Python not so accurate

python - scikit-learn 和 sklearn 的区别

java - 使用 Python 创建和实现接口(interface)?