Python将文本写入.tar.gz [英] Python write text to .tar.gz
问题描述
我正在寻找一种使用python在.tar.gz文件中直接写入文本文件(OnTheFly)的可能性.最好的办法是像fobj = open (arg.file, "a")
这样的解决方案来附加文本.
I look for a possibility to write a text file directly (OnTheFly) in a .tar.gz file with python. The best would be a solution like fobj = open (arg.file, "a")
to append the text.
我想对不允许拆分的长日志文件使用此功能.
I want to use this feature for long log files that you are not allowed to split.
预先感谢
推荐答案
是的,这是可能的,但是很可能不是您想要使用它的方式.
Yes, this is possible, but most likely not in the way you'd like to use it.
.tar.gz
实际上是两件事情: gz
或 gzip
用于压缩,但是此工具只能压缩单个文件,因此,如果要将多个文件压缩到一个压缩的归档文件中,则需要先加入这些文件.这就是 tar
所做的事情,它需要多个文件并将它们加入到存档中
.tar.gz
is actually two things in one: 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
does, it takes multiple files and joins them to an archive.
如果您只有一个长日志文件,只需 gzip
ing 即可.为此,Python具有 gzip
模块,您可以直接将其写入压缩文件:
If you have a single long logfile, just gzip
ing it would be easier. For this, Python has the gzip
module, you can write directly into the compressed file:
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可能不是记录日志的最佳解决方案.
If you definitely need to write into a tar
-archive, you can use Python's tarfile
module. However, this module does not support appending to a file (mode 'a'
), therefore a tarfile might not be the best solution for logging.
这篇关于Python将文本写入.tar.gz的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!