]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.13] gh-86608: Improve and restructure tarfile examples (GH-121771) (#136867)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sun, 20 Jul 2025 13:16:26 +0000 (15:16 +0200)
committerGitHub <noreply@github.com>
Sun, 20 Jul 2025 13:16:26 +0000 (14:16 +0100)
gh-86608: Improve and restructure tarfile examples (GH-121771)

Add an example on how to write a tarfile to stdout; general improvements.
(cherry picked from commit cc81b4e501138b5793d419c81c3a2859a17207a7)

Co-authored-by: Dominic H <dom@dominic.sk>
Co-authored-by: Adam Turner <9087854+AA-Turner@users.noreply.github.com>
Doc/library/tarfile.rst

index e821989396051f4e7d10d7cb140119a6abfb079e..5532ffa1ad27f57765c3d18b55ece72f4e579e19 100644 (file)
@@ -1304,6 +1304,9 @@ Command-line options
 Examples
 --------
 
+Reading examples
+~~~~~~~~~~~~~~~~~~~
+
 How to extract an entire tar archive to the current working directory::
 
    import tarfile
@@ -1326,6 +1329,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
@@ -1341,19 +1361,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`::