Python write text to .tar.gz
Question: 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


Answer: 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`](https://en.wikipedia.org/wiki/Gzip) or
[`gzip`](https://en.wikipedia.org/wiki/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`](https://en.wikipedia.org/wiki/Tar_\(computing\))
does, it takes multiple files and joins them to an archive.

If you have a single long logfile, just
[`gzip`ing](https://en.wikipedia.org/wiki/Gzip) it would be easier. For this,
Python has the [`gzip`](https://docs.python.org/3.4/library/gzip.html) 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`](https://docs.python.org/2/library/tarfile.html) module. However,
this module does not support _appending_ to a file (mode `'a'`), therefore a
tarfile might not be the best solution for logging.

