Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Nota
Aunque tarfile implementa un formato Unix, puede usarse también para crear y
leer archivos tar en Microsoft Windows.
Archivos Tar de prueba
La función is_tarfile() devuelve un valor booleano que indica si o no, el nombre
de archivo pasado como argumento hace referencia a un archivo tar válido.
tarfile_is_tarfile.py
import tarfile
$ python3 tarfile_is_tarfile.py
README.txt False
example.tar True
bad_example.tar False
notthere.tar [Errno 2] No such file or directory:
'notthere.tar'
Para leer los nombres de los archivos en un archivo existente, usa getnames() .
tarfile_getnames.py
import tarfile
El valor de retorno es una lista de cadenas con los nombres del contenido del
archivo.
$ python3 tarfile_getnames.py
['index.rst', 'README.txt']
Además de los nombres, los metadatos sobre los miembros del archivo están
disponibles como instancias de objetos TarInfo .
tarfile_getmembers.py
import tarfile
import time
$ python3 tarfile_getmembers.py
index.rst
Modified: Fri Aug 19 16:27:54 2016
Mode : 0o644
Type : b'0'
Size : 9878 bytes
README.txt
Modified: Fri Aug 19 16:27:54 2016
Mode : 0o644
Type : b'0'
Size : 75 bytes
tarfile_getmember.py
import tarfile
import time
$ python3 tarfile_getmember.py
README.txt is 75 bytes
ERROR: Did not find notthere.txt in tar archive
tarfile_extractfile.py
import tarfile
$ python3 tarfile_extractfile.py
README.txt :
The examples for the tarfile module use this file and
example.tar as data.
tarfile_extract.py
import tarfile
import os
os.mkdir('outdir')
with tarfile.open('example.tar', 'r') as t:
t.extract('README.txt', 'outdir')
print(os.listdir('outdir'))
El miembro o miembros se leen del archivo y se escriben en el sistema de
archivos, comenzando en el directorio nombrado en los argumentos.
$ python3 tarfile_extract.py
['README.txt']