In this section, we are going to learn about the tarfile module. We'll also learn about testing the entered filename, assessing whether it's a valid archive filename or not. We'll look at how to add a new file into the already archived file, how we can read metadata using the tarfile module, and how to extract the files from an archive using the extractall() function.
First, we will test whether the entered filename is a valid archive file or not. To test this, the tarfile module has the is_tarfile() function, which returns a Boolean value.
Create a script called check_archive_file.py and write the following content in it:
import tarfile
for f_name in ['hello.py', 'work.tar.gz', 'welcome.py', 'nofile.tar', 'sample.tar.xz']:
try:
print('{:} {}'.format(f_name, tarfile.is_tarfile(f_name)))
...