Skip to content

Commit cc81b4e

Browse files
gh-86608: Improve and restructure tarfile examples (#121771)
Add an example on how to write a tarfile to stdout; general improvements. Co-authored-by: Adam Turner <[email protected]>
1 parent c6e6fe9 commit cc81b4e

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
@@ -1353,6 +1353,9 @@ Command-line options
13531353
Examples
13541354
--------
13551355

1356+
Reading examples
1357+
~~~~~~~~~~~~~~~~~~~
1358+
13561359
How to extract an entire tar archive to the current working directory::
13571360

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

1381+
How to read a gzip compressed tar archive and display some member information::
1382+
1383+
import tarfile
1384+
tar = tarfile.open("sample.tar.gz", "r:gz")
1385+
for tarinfo in tar:
1386+
print(tarinfo.name, "is", tarinfo.size, "bytes in size and is ", end="")
1387+
if tarinfo.isreg():
1388+
print("a regular file.")
1389+
elif tarinfo.isdir():
1390+
print("a directory.")
1391+
else:
1392+
print("something else.")
1393+
tar.close()
1394+
1395+
Writing examples
1396+
~~~~~~~~~~~~~~~~
1397+
13781398
How to create an uncompressed tar archive from a list of filenames::
13791399

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

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

1395-
import tarfile
1396-
tar = tarfile.open("sample.tar.gz", "r:gz")
1397-
for tarinfo in tar:
1398-
print(tarinfo.name, "is", tarinfo.size, "bytes in size and is ", end="")
1399-
if tarinfo.isreg():
1400-
print("a regular file.")
1401-
elif tarinfo.isdir():
1402-
print("a directory.")
1403-
else:
1404-
print("something else.")
1405-
tar.close()
1417+
import sys
1418+
import tarfile
1419+
with tarfile.open("sample.tar.gz", "w|gz", fileobj=sys.stdout.buffer) as tar:
1420+
for name in ["foo", "bar", "quux"]:
1421+
tar.add(name)
14061422

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

0 commit comments

Comments
 (0)