|
| 1 | +import tarfile |
| 2 | +import os |
| 3 | + |
| 4 | + |
| 5 | +def list_tar(archive, verbosity): |
| 6 | + """List a TAR archive with the tarfile Python module.""" |
| 7 | + try: |
| 8 | + with tarfile.open(archive) as tfile: |
| 9 | + tfile.list(verbose=verbosity > 1) |
| 10 | + except Exception as err: |
| 11 | + msg = "error listing %s: %s" % (archive, err) |
| 12 | + print(msg) |
| 13 | + return None |
| 14 | + |
| 15 | + |
| 16 | +test_tar = list_tar |
| 17 | + |
| 18 | + |
| 19 | +def extract_tar(archive, outdir): |
| 20 | + """Extract a TAR archive with the tarfile Python module.""" |
| 21 | + try: |
| 22 | + with tarfile.open(archive) as tfile: |
| 23 | + tfile.extractall(path=outdir) |
| 24 | + except Exception as err: |
| 25 | + msg = "error extracting %s: %s" % (archive, err) |
| 26 | + print(msg) |
| 27 | + return None |
| 28 | + |
| 29 | + |
| 30 | +def create_tar(archive, folder_name, compression=None): |
| 31 | + """Create a TAR archive with the tarfile Python module.""" |
| 32 | + mode = "w:" |
| 33 | + if compression is not None: |
| 34 | + mode = get_tar_mode(compression) |
| 35 | + try: |
| 36 | + with tarfile.open(archive, mode) as tfile: |
| 37 | + for filename in os.listdir(folder_name): |
| 38 | + tfile.add(folder_name + filename, arcname=filename) |
| 39 | + except Exception as err: |
| 40 | + msg = "error creating %s: %s" % (archive, err) |
| 41 | + print(msg) |
| 42 | + return None |
| 43 | + |
| 44 | + |
| 45 | +def get_tar_mode(compression): |
| 46 | + """Determine tarfile open mode according to the given compression.""" |
| 47 | + if compression == 'gzip': |
| 48 | + return 'w:gz' |
| 49 | + if compression == 'bzip2': |
| 50 | + return 'w:bz2' |
| 51 | + if compression == 'lzma': |
| 52 | + return 'w:xz' |
| 53 | + if compression: |
| 54 | + msg = 'pytarfile does not support %s for tar compression' |
| 55 | + print(msg) |
| 56 | + # no compression |
| 57 | + return 'w' |
0 commit comments