TarFile.
How It Works
TarFile.add(path, arcname=...) adds an existing file or directory to an open TAR archive. Directory additions are recursive by default, so inspect your source paths and choose an internal archive name deliberately.
Step-by-Step Example
from pathlib import Path
import tarfile
import tempfile
with tempfile.TemporaryDirectory() as temporary_directory:
source_path = Path(temporary_directory) / 'report.txt'
source_path.write_text('status=ready', encoding='utf-8')
archive_path = Path(temporary_directory) / 'report.tar'
with tarfile.open(archive_path, 'w') as archive:
archive.add(source_path, arcname='reports/report.txt')
with tarfile.open(archive_path) as archive:
print(archive.getnames())
Understanding the Example
- The with block manages the opened resource and closes it when the block finishes, including when an exception occurs.
- The expression "Path(temporary_directory) / 'report.txt'" supplies the value stored as 'source_path'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
['reports/report.txt']
Where This Fits in a Real Program
A practical archive workflow has separate decisions for selection, compression, extraction and verification. When files come from other people, inspect paths, member counts and uncompressed sizes before writing anything; a successful decompression does not establish that its contents are trustworthy.
Practice: Try It Yourself
Write one temporary source file into an archive under a chosen internal name.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Accidentally archiving an entire private directory when only one report was intended.
- Do not mistake successful decoding or parsing for trust in the contents.
Key Takeaways
- TarFile.
- TarFile.add(path, arcname=...) adds an existing file or directory to an open TAR archive.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.