How are files extracted from a tar file using Python?

PythonServer Side ProgrammingProgramming

You can use the tarfile module to read and write tar files. To extract a tar file, you need to first open the file and then use the extract method of the tarfile module.

For example

import tarfile
my_tar = tarfile.open('my_tar.tar.gz')
my_tar.extractall('./my_folder') # specify which folder to extract to
my_tar.close()

This will extract the my_tar.tar.gz file's contents to my_folder.

You can also extract individual files from the tar using extract(filename, path).

For example

import tarfile
my_tar = tarfile.open('my_tar.tar.gz')
my_tar.extract('hello.txt','./my_folder')
my_tar.close()
raja
Published on 28-Dec-2017 11:18:23
Advertisements