Skip to content

[3.14] gh-86608: Improve and restructure tarfile examples (GH-121771) #136866

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 20, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 28 additions & 12 deletions Doc/library/tarfile.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1353,6 +1353,9 @@ Command-line options
Examples
--------

Reading examples
~~~~~~~~~~~~~~~~~~~

How to extract an entire tar archive to the current working directory::

import tarfile
Expand All @@ -1375,6 +1378,23 @@ a generator function instead of a list::
tar.extractall(members=py_files(tar))
tar.close()

How to read a gzip compressed tar archive and display some member information::

import tarfile
tar = tarfile.open("sample.tar.gz", "r:gz")
for tarinfo in tar:
print(tarinfo.name, "is", tarinfo.size, "bytes in size and is ", end="")
if tarinfo.isreg():
print("a regular file.")
elif tarinfo.isdir():
print("a directory.")
else:
print("something else.")
tar.close()

Writing examples
~~~~~~~~~~~~~~~~

How to create an uncompressed tar archive from a list of filenames::

import tarfile
Expand All @@ -1390,19 +1410,15 @@ The same example using the :keyword:`with` statement::
for name in ["foo", "bar", "quux"]:
tar.add(name)

How to read a gzip compressed tar archive and display some member information::
How to create and write an archive to stdout using
:data:`sys.stdout.buffer <sys.stdout>` in the *fileobj* parameter
in :meth:`TarFile.add`::

import tarfile
tar = tarfile.open("sample.tar.gz", "r:gz")
for tarinfo in tar:
print(tarinfo.name, "is", tarinfo.size, "bytes in size and is ", end="")
if tarinfo.isreg():
print("a regular file.")
elif tarinfo.isdir():
print("a directory.")
else:
print("something else.")
tar.close()
import sys
import tarfile
with tarfile.open("sample.tar.gz", "w|gz", fileobj=sys.stdout.buffer) as tar:
for name in ["foo", "bar", "quux"]:
tar.add(name)

How to create an archive and reset the user information using the *filter*
parameter in :meth:`TarFile.add`::
Expand Down
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy