Python write text to .tar.gz

守給你的承諾、 提交于 2019-12-10 17:17:10

问题


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.

Thanks in advance


回答1:


Yes, this is possible, but most likely not in the way you'd like to use it.

.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.

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")

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.



来源:https://stackoverflow.com/questions/31240550/python-write-text-to-tar-gz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!