Python将文本写入.tar.gz [英] Python write text to .tar.gz

查看:289
本文介绍了Python将文本写入.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 gziping 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆