[Tutor] How to read content in a tar file with tarfile module
Carlos Hanson
chanson at ttsd.k12.or.us
Tue Oct 10 20:36:57 CEST 2006
On Tue, October 10, 2006 11:15 am, Magnus Wirström wrote:
> Hi everyone
>
> I have written a app that makes a tar file and all works well... Now
> i want to expand that app so it can read read the tar and give me the
> contents of the tar file. How is the best way to do this ? I can't
> find a "listdir" like function in tarfile. Can anyone point me in the
> right direction? Thanks Magnus
There are two choices depending on your needs. First is the list()
method of a TarFile object:
>>> from tarfile import TarFile
>>> tar = TarFile('files.tar')
>>> tar.list()
-rw-r--r-- chanson/chanson 0 2006-10-10 11:31:08 file.1
-rw-r--r-- chanson/chanson 0 2006-10-10 11:31:11 file.2
-rw-r--r-- chanson/chanson 0 2006-10-10 11:31:15 file.3
The second option is the getmembers() method which returns TarInfo
objects:
>>> members = tar.getmembers()
>>> for member in members:
... print member.name
...
file.1
file.2
file.3
>>> for member in members:
... print "%s %s/%s\t%s %s %s" % (
... member.mode, member.uname, member.gname,
... member.size, member.mtime, member.name)
...
420 chanson/chanson 0 1160505068 file.1
420 chanson/chanson 0 1160505071 file.2
420 chanson/chanson 0 1160505075 file.3
--
Carlos Hanson
Web and System Administrator
Tigard-Tualatin School District
503.431.4053
More information about the Tutor
mailing list