I wanted to make a backup, so on Google [python + directory + compression] search for. Note that Zubari did not hit the top of the search.
tar_dir.py
import tarfile
#Directory name
dir_name = 'data'
#Compressed file name
tar_name = dir_name + '.tar.gz'
#Compression process
archive = tarfile.open(tar_name, mode='w:gz')
archive.add(dir_name)
archive.close()
If you specify a directory, you can compress the directory.
Such directories can be compressed. data/ ├ mydir/ │ ├ nestdir/ │ │ ├ aaa.txt │ │ ├ bbb.txt │ │ └ foo.csv │ ├ bar.csv │ ├ ccc.txt │ └ ddd.txt ├ eee.txt ├ fff.txt └ hoge.csv
The tarfile has the following modes. (Investigated with Python 3.5)
Grammar 1: filemode
Grammar 2: filemode [: compression]
(for random seek)
Grammar 3: filemode [| compression]
(for streams)
Default: r
mode | action |
---|---|
'r'Or'r:*' | Transparent for compression method, open for reading |
'r:' | Uncompressed and open for reading |
'r:gz' | Open for reading with gzip compression |
'r:bz2' | Open for reading with bzip2 compression |
'r:xz' | Open for reading with lzma compression |
'x'Or'x:' | Create tarfile exclusively without compression.FileExistsError if the file exists |
'x:gz' | Create tarfile with gzip compression.FileExistsError if the file exists |
'x:bz2' | Create tarfile with bzip2 compression.FileExistsError if the file exists |
'x:xz' | Create tarfile with lzma compression.FileExistsError if the file exists |
'a'Or'a:' | Uncompressed and open for appending.If the file does not exist, create a new one |
'w'Or'w:' | Uncompressed and open for writing |
'w:gz' | Open for writing with gzip compression |
'w:bz2' | Open for writing with bzip2 compression |
'w:xz' | Open for writing with lzma compression |
'r|*' | Transparently open stream for reading regarding compression method |
'r|' | Open uncompressed stream for reading |
'r|gz' | Open gzip compressed stream for reading |
'r|bz2' | Open bzip2 compressed stream for reading |
'r|xz' | Open lzma compressed stream for reading |
'w|' | Open uncompressed stream for writing |
'w|gz' | open stream for writing |
'w|bz2' | open stream for writing |
'w|xz' | open stream for writing |
|
(full-width) with |
(half-width).You can archive and compress directories from the command line.
$ python -m tarfile -c tar_name.tar.gz dir_name/
It switches the compression method according to the extension of the tar file.
extension | Compression method |
---|---|
.gz | gz |
.tgz | gz |
.xz | xz |
.txz | xz |
.bz2 | bz2 |
.tbz | bz2 |
.tbz2 | bz2 |
.tb2 | bz2 |
List of command line options for tarfile
option | フルoption | argument | Remarks |
---|---|---|---|
-v | --verbose | Default is False | |
-l | --list | <tarfile> | |
-e | --extract | <tarfile> <output_dir> | |
-c | --create | <name> <file> | |
-t | --test | <tarfile> |
Original document tarfile (link)