Skip to content

Commit 74607b1

Browse files
miss-islingtonGovernmentPlatesAA-Turner
authored
[3.13] gh-86608: Improve and restructure tarfile examples (GH-121771) (#136867)
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 cc81b4e) Co-authored-by: Dominic H <dom@dominic.sk> Co-authored-by: Adam Turner <9087854+AA-Turner@users.noreply.github.com>
1 parent cc8b9d6 commit 74607b1

File tree

1 file changed

+28
-12
lines changed

1 file changed

+28
-12
lines changed

Doc/library/tarfile.rst

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1304,6 +1304,9 @@ Command-line options
13041304
Examples
13051305
--------
13061306

1307+
Reading examples
1308+
~~~~~~~~~~~~~~~~~~~
1309+
13071310
How to extract an entire tar archive to the current working directory::
13081311

13091312
import tarfile
@@ -1326,6 +1329,23 @@ a generator function instead of a list::
13261329
tar.extractall(members=py_files(tar))
13271330
tar.close()
13281331

1332+
How to read a gzip compressed tar archive and display some member information::
1333+
1334+
import tarfile
1335+
tar = tarfile.open("sample.tar.gz", "r:gz")
1336+
for tarinfo in tar:
1337+
print(tarinfo.name, "is", tarinfo.size, "bytes in size and is ", end="")
1338+
if tarinfo.isreg():
1339+
print("a regular file.")
1340+
elif tarinfo.isdir():
1341+
print("a directory.")
1342+
else:
1343+
print("something else.")
1344+
tar.close()
1345+
1346+
Writing examples
1347+
~~~~~~~~~~~~~~~~
1348+
13291349
How to create an uncompressed tar archive from a list of filenames::
13301350

13311351
import tarfile
@@ -1341,19 +1361,15 @@ The same example using the :keyword:`with` statement::
13411361
for name in ["foo", "bar", "quux"]:
13421362
tar.add(name)
13431363

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

1346-
import tarfile
1347-
tar = tarfile.open("sample.tar.gz", "r:gz")
1348-
for tarinfo in tar:
1349-
print(tarinfo.name, "is", tarinfo.size, "bytes in size and is ", end="")
1350-
if tarinfo.isreg():
1351-
print("a regular file.")
1352-
elif tarinfo.isdir():
1353-
print("a directory.")
1354-
else:
1355-
print("something else.")
1356-
tar.close()
1368+
import sys
1369+
import tarfile
1370+
with tarfile.open("sample.tar.gz", "w|gz", fileobj=sys.stdout.buffer) as tar:
1371+
for name in ["foo", "bar", "quux"]:
1372+
tar.add(name)
13571373

13581374
How to create an archive and reset the user information using the *filter*
13591375
parameter in :meth:`TarFile.add`::

0 commit comments

Comments
 (0)