Creating archives

Now, we are going to write a script called shutil_make_archive.py and write the following content in it:

import tarfile
import shutil
import sys

shutil.make_archive(
'work_sample', 'gztar',
root_dir='..',
base_dir='work',
)
print('Archive contents:')
with tarfile.open('work_sample.tar.gz', 'r') as t_file:
for names in t_file.getnames():
print(names)

Run the program and you'll get the following output:

$ python3 shutil_make_archive.py
Archive contents:
work
work/bye.py
work/shutil_make_archive.py
work/welcome.py
work/hello.py

In the preceding example, to create an archive file, we used the shutil and tarfile modules of Python. In shutil.make_archive(), we specified work_sample, which will be the name of the archive file and will be in gz format. We've specified our work directory name in the base directory attribute. Finally, we printed the names of files that are archived.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset