简体   繁体   English

如何在Python中压缩已处理的文本文件?

[英]How to compress a processed text file in Python?

I have a text file which I constantly append data to. 我有一个文本文件,我不断将数据附加到该文件。 When processing is done I need to gzip the file. 处理完成后,我需要gzip文件。 I tried several options like shutil.make_archive , tarfile , gzip but could not eventually do it. 我尝试了几个选项,如shutil.make_archivetarfilegzip但最终无法做到。 Is there no simple way to compress a file without actually writing to it? 没有实际写入文件的简单方法来压缩文件吗?

Let's say I have mydata.txt file and I want it to be gzipped and saved as mydata.txt.gz . 假设我有mydata.txt文件,我希望将其压缩并另存为mydata.txt.gz

I don't see the problem. 我没看到问题。 You should be able to use eg the gzip module just fine, something like this: 您应该可以使用gzip模块 ,例如:

inf = open("mydata.txt", "rb")
outf = gzip.open("file.txt.gz", "wb")
outf.write(inf.read())
outf.close()
inf.close()

There's no problem with the file being overwritten, the name given to gzip.open() is completely independent of the name given to plain open() . 覆盖文件没有问题,给gzip.open()的名称完全独立于给普通open()的名称。

如果要压缩文件而不写入文件,则可以使用Python库subprocess os.systempopenos.system运行shell命令,例如gzip

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM