Python 将文本写入 .tar.gz

Python write text to .tar.gz

我正在寻找一种可能性,可以直接在 .tar.gz 文件中写入文本文件 (OnTheFly) python。最好的办法是像 fobj = open (arg.file, "a") 这样的解决方案来附加文本。

我想对不允许拆分的长日志文件使用此功能。

提前致谢

是的,这是可能的,但很可能不是您想要的使用方式。

.tar.gz 实际上是两件事合二为一:gz or gzip is being used for compression, but this tool can only compress single files, so if you want to zip multiple files to a compressed archive, you would need to join these files first. This is what tar 确实如此,它需要多个文件并将它们加入一个存档。

如果你有一个单独的长日志文件,只有gziping it would be easier. For this, Python has the gzip模块,你可以直接写入压缩文件:

import gzip
with gzip.open('logfile.gz', 'a') as log:
    # Needs to be a bytestring in Python 3
    log.write(b"I'm a log message.\n")

如果您确实需要写入 tar 存档,您可以使用 Python 的 tarfile 模块。但是,此模块不支持 附加 到文件(模式 'a'),因此 tarfile 可能不是记录日志的最佳解决方案。