Unpacking archives

To unpack the archives, the shutil module has the unpack_archive() function. Using this function, we can extract the archive files. We passed the archive filename and the directory where we want to extract the contents. If no directory name is passed, then it will extract the contents into your current working directory.

Now, create a script called shutil_unpack_archive.py and write the following code in it:

import pathlib
import shutil
import sys
import tempfile
with tempfile.TemporaryDirectory() as d:
shutil.unpack_archive('work_sample.tar.gz', extract_dir='/home/student/work',)
prefix_len = len(d) + 1
for extracted in pathlib.Path(d).rglob('*'):
print(str(extracted)[prefix_len:])

Run the script as follows:

student@ubuntu:~/work$ python3 shutil_unpack_archive.py

Now, check your work/ directory and you will find the work/ folder in it, which will have the extracted files.

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

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