Examples
--------
+Reading examples
+~~~~~~~~~~~~~~~~~~~
+
How to extract an entire tar archive to the current working directory::
import tarfile
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
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`::