@@ -1353,6 +1353,9 @@ Command-line options
1353
1353
Examples
1354
1354
--------
1355
1355
1356
+ Reading examples
1357
+ ~~~~~~~~~~~~~~~~~~~
1358
+
1356
1359
How to extract an entire tar archive to the current working directory::
1357
1360
1358
1361
import tarfile
@@ -1375,6 +1378,23 @@ a generator function instead of a list::
1375
1378
tar.extractall(members=py_files(tar))
1376
1379
tar.close()
1377
1380
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
+
1378
1398
How to create an uncompressed tar archive from a list of filenames::
1379
1399
1380
1400
import tarfile
@@ -1390,19 +1410,15 @@ The same example using the :keyword:`with` statement::
1390
1410
for name in ["foo", "bar", "quux"]:
1391
1411
tar.add(name)
1392
1412
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 `::
1394
1416
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)
1406
1422
1407
1423
How to create an archive and reset the user information using the *filter *
1408
1424
parameter in :meth: `TarFile.add `::
0 commit comments