How can I create a .tar.gz file with compression in Python?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
In this tar.gz file compress in open view directory In solve use os.path.basename(file_directory)
its use in tar.gz file compress in directory
If you want to create a tar.bz2 compressed file, just replace file extension name with ".tar.bz2" and "w:gz" with "w:bz2".
You call tarfile.open with
mode='w:gz'
, meaning "Open for gzip compressed writing."You'll probably want to end the filename (the
name
argument toopen
) with.tar.gz
, but that doesn't affect compression abilities.BTW, you usually get better compression with a mode of
'w:bz2'
, just liketar
can usually compress even better withbzip2
than it can compress withgzip
.To build a
.tar.gz
(aka.tgz
) for an entire directory tree:This will create a gzipped tar archive containing a single top-level folder with the same name and contents as
source_dir
.Previous answers advise using the
tarfile
Python module for creating a.tar.gz
file in Python. That's obviously a good and Python-style solution, but it has serious drawback in speed of the archiving. This question mentions thattarfile
is approximately two times slower than thetar
utility in Linux. According to my experience this estimation is pretty correct.So for faster archiving you can use the
tar
command usingsubprocess
module: