leggere il contenuto dei file tar senza scompattando essa, nello script python
Domanda
Ho un file tar che ha numero di file all'interno di esso. Ho bisogno di scrivere uno script python che leggere il contenuto dei file e dà il conteggio o caratteri totali, compreso il numero totale di lettere, spazi, caratteri di fine riga, tutto, senza scompattando il file tar.
Soluzione
è possibile utilizzare getmembers ()
>>> import tarfile
>>> tar = tarfile.open("test.tar")
>>> tar.getmembers()
Dopo di che, è possibile utilizzare extractfile () per estrarre i membri come oggetto file. Solo un esempio
import tarfile,os
import sys
os.chdir("/tmp/foo")
tar = tarfile.open("test.tar")
for member in tar.getmembers():
f=tar.extractfile(member)
content=f.read()
print "%s has %d newlines" %(member, content.count("\n"))
print "%s has %d spaces" % (member,content.count(" "))
print "%s has %d characters" % (member, len(content))
sys.exit()
tar.close()
Con l'oggetto file "f" nell'esempio di cui sopra, è possibile utilizzare read (), readlines (), ecc
Altri suggerimenti
è necessario utilizzare il modulo tarfile. In particolare, si utilizza un'istanza della classe TarFile per accedere al file, e quindi accedere ai nomi con TarFile.getnames ()
| getnames(self)
| Return the members of the archive as a list of their names. It has
| the same order as the list returned by getmembers().
Se invece volete leggere il contenuto , quindi si utilizza questo metodo
| extractfile(self, member)
| Extract a member from the archive as a file object. `member' may be
| a filename or a TarInfo object. If `member' is a regular file, a
| file-like object is returned. If `member' is a link, a file-like
| object is constructed from the link's target. If `member' is none of
| the above, None is returned.
| The file-like object is read-only and provides the following
| methods: read(), readline(), readlines(), seek() and tell()
Un'implementazione dei metodi di cui parla @ stefano-Borini Accedere a un membro archivi tar con il nome del file in questo modo
#python3
myFile = myArchive.extractfile(
dict(zip(
myArchive.getnames(),
myArchive.getmembers()
))['path/to/file']
).read()`
Credits:
- dict(zip( da href="https://stackoverflow.com/a/209854/1695680"> https://stackoverflow.com/a/209854/1695680
- tarfile.getnames da href="https://stackoverflow.com/a/2018523/1695680"> https://stackoverflow.com/a/2018523/1695680
- Inoltre, per i miei usi, leggere un archivio tar dal buffer Come costruire un oggetto di TarFile in memoria dal buffer di byte in Python 3?