@@ -1304,6 +1304,9 @@ Command-line options
13041304Examples
13051305--------
13061306
1307+ Reading examples
1308+ ~~~~~~~~~~~~~~~~~~~
1309+
13071310How 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+
13291349How 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
13581374How to create an archive and reset the user information using the *filter *
13591375parameter in :meth: `TarFile.add `::
0 commit comments