import tarfile

# Opening TAR Archives
with tarfile.open("example.tar", "r") as tar_file:
    print(tar_file.getnames())

"""
Mode 	Action
r 		Opens archive for reading with transparent compression
r:gz 	Opens archive for reading with gzip compression
r:bz2 	Opens archive for reading with bzip2 compression
r:xz 	Opens archive for reading with lzma compression
w 		Opens archive for uncompressed writing
w:gz 	Opens archive for gzip compressed writing
w:xz 	Opens archive for lzma compressed writing
a 		Opens archive for appending with no compression
"""


import tarfile

# To read an uncompressed TAR file and retrieve the names of the files in it
tar = tarfile.open("example.tar", mode="r")
tar.getnames()

for entry in tar.getmembers():
    print(entry.name)
    print(" Modified:", time.ctime(entry.mtime))
    print(" Size    :", entry.size, "bytes")
    print()


# To extract a single file from a TAR archive
tar.extract("README.md")


# To unpack or extract everything from the archive
tar.extractall(path="extracted/")


# To extract a file object for reading or writing
f = tar.extractfile("app.py")
f.read()
tar.close()


# Creating New TAR Archives
import tarfile

file_list = ["app.py", "config.py", "CONTRIBUTORS.md", "tests.py"]
with tarfile.open("packages.tar", mode="w") as tar:
    for file in file_list:
        tar.add(file)

# Read the contents of the newly created archive
with tarfile.open("package.tar", mode="r") as t:
    for member in t.getmembers():
        print(member.name)


# To add new files to an existing archive
with tarfile.open("package.tar", mode="a") as tar:
    tar.add("foo.bar")

with tarfile.open("package.tar", mode="r") as tar:
    for member in tar.getmembers():
        print(member.name)


# Working With Compressed Archives
files = ["app.py", "config.py", "tests.py"]
with tarfile.open("packages.tar.gz", mode="w:gz") as tar:
    tar.add("app.py")
    tar.add("config.py")
    tar.add("tests.py")

with tarfile.open("packages.tar.gz", mode="r:gz") as t:
    for member in t.getmembers():
        print(member.name)


# An Easier Way of Creating Archives
import shutil

# shutil.make_archive(base_name, format, root_dir)
shutil.make_archive("data/backup", "tar", "data/")

# To extract the archive
shutil.unpack_archive("backup.tar", "extract_dir/")
