Reputation: 85
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
Upvotes: 4
Views: 2416
Reputation: 3991
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 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")
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.
Upvotes: 4