Python: create compressed tar file for streaming

I need to create a tar.gzipped text file. Is there a way to create a file for permanent recording (to do something like compressedFile.write("some text") ), or do I need to create the original text file first and compress it after that?

This will be very unfortunate, as the file must be very long and well compressible.

+6
source share
1 answer

Here is an example of how to write a compressed tar file from a Python script:

 import StringIO import tarfile tar = tarfile.open('example.tar.gz', 'w:gz') # create a file record data = StringIO.StringIO('this is some text') info = tar.tarinfo() info.name = 'foo.txt' info.uname = 'pat' info.gname = 'users' info.size = data.len # add the file to the tar and close it tar.addfile(info, data) tar.close() 

Result:

 % tar tvf example.tar.gz -rw-r--r-- 0 pat users 17 Dec 31 1969 foo.txt 
+5
source

Source: https://habr.com/ru/post/886011/


All Articles