Backports Tarfile
backports.tarfile provides a backport of the CPython standard library's `tarfile` module, allowing users on older Python versions (>=3.8) to access newer features and bug fixes related to tar archive handling. The current version is 1.2.0, released recently, with several updates in Spring 2024.
Warnings
- gotcha ImportError due to namespace package conflicts, particularly with `setuptools` versions (e.g., 71.0.0+). Users might encounter `ImportError: cannot import name 'tarfile' from 'backports'`.
- gotcha Security Vulnerabilities in Backported `tarfile` Extraction Filtering (pre-Python 3.12). The backported tarfile extraction filtering feature, intended for security, was incomplete and could introduce new security issues if projects switched from custom inspection to relying solely on these filters.
- gotcha Misunderstanding its purpose: This library is a backport. If your Python version natively includes the `tarfile` features you need, you should use the standard library's `tarfile` directly, rather than the backport, to avoid unnecessary dependencies or potential conflicts.
Install
-
pip install backports-tarfile
Imports
- tarfile
from backports import tarfile
Quickstart
import os
from backports import tarfile
# Create a dummy file
with open('example.txt', 'w') as f:
f.write('Hello, backported tarfile!')
# Create a tar.gz archive
with tarfile.open('example.tar.gz', 'w:gz') as tar:
tar.add('example.txt')
print('Archive created: example.tar.gz')
# Extract the archive
with tarfile.open('example.tar.gz', 'r:gz') as tar:
tar.extractall(path='./extracted_archive')
print('Archive extracted to ./extracted_archive')
# Clean up
os.remove('example.txt')
os.remove('example.tar.gz')
os.remove('./extracted_archive/example.txt')
os.rmdir('./extracted_archive')