How to Extract Tar File in Python: Simple Guide
Use Python's
tarfile module to open and extract tar files. Call tarfile.open() with the file path, then use extractall() to unpack all contents.Syntax
To extract a tar file in Python, use the tarfile module. The main steps are:
tarfile.open(filename, mode): Opens the tar file. Use mode'r'for reading.extractall(path): Extracts all files to the specified directory. Ifpathis omitted, extracts to the current directory.close(): Closes the tar file after extraction.
python
import tarfile tar = tarfile.open('archive.tar', 'r') tar.extractall(path='destination_folder') tar.close()
Example
This example shows how to extract all files from sample.tar into a folder named extracted_files. It creates the folder if it doesn't exist.
python
import tarfile import os file_path = 'sample.tar' destination = 'extracted_files' if not os.path.exists(destination): os.makedirs(destination) with tarfile.open(file_path, 'r') as tar: tar.extractall(path=destination) print(f'Files extracted to {destination}')
Output
Files extracted to extracted_files
Common Pitfalls
Common mistakes when extracting tar files include:
- Not closing the tar file, which can lock the file or cause resource leaks.
- Extracting files without specifying a safe destination, which may overwrite important files.
- Trying to extract compressed tar files (like .tar.gz) without the correct mode (use
'r:gz'for gzip compressed files).
Always use with statement to handle files safely.
python
import tarfile # Wrong: Not using 'with' and not closing # tar = tarfile.open('archive.tar', 'r') # tar.extractall() # Right: Using 'with' to auto-close with tarfile.open('archive.tar', 'r') as tar: tar.extractall()
Quick Reference
| Function | Description |
|---|---|
| tarfile.open(filename, mode) | Open a tar file with mode 'r', 'r:gz', or 'r:bz2' |
| extractall(path=None) | Extract all files to the given path or current directory |
| getnames() | List all file names inside the tar archive |
| close() | Close the tar file (if not using 'with') |
Key Takeaways
Use the tarfile module's open() and extractall() to extract tar files easily.
Always use a 'with' block to open tar files for safe automatic closing.
Specify the correct mode for compressed tar files like 'r:gz' for .tar.gz files.
Extract files to a dedicated folder to avoid overwriting important files.
Check the contents with getnames() before extracting if unsure.