2010-01-07 202 views
46

我有一个tar文件,里面有一些文件。 我需要编写一个python脚本,它将读取文件的内容,并给出包括总字符数,空格,换行符,所有内容在内的总数,而不需要解压tar文件。在没有解压缩的情况下读取tar文件内容,在python脚本中

+0

你怎么能指望的字符/字母/空间/无解压那些别处寄托都tar归档? – YOU 2010-01-07 06:17:35

+5

这正是问题所在。 – 2013-01-15 14:34:43

回答

83

你可以使用getmembers()

>>> import tarfile 
>>> tar = tarfile.open("test.tar") 
>>> tar.getmembers() 

之后,你可以使用extractfile()的成员提取物作为文件对象。只是一个例子

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() 

随着在上面的例子中文件对象“F”,你可以使用read(),readlines方法()等

+9

“可以改为”for tar for成员“,它可以是一个生成器或一个迭代器(我不知道是哪一个)。但它一次只能获得一个成员。 – huggie 2011-12-28 09:24:04

+1

我刚刚有一个类似的问题,但tarfile模块似乎吃我的内存,即使我用'r |''选项。 – devsnd 2012-05-21 17:39:52

+1

啊。我解决了它。假设你会像huggie暗示的那样编写代码,你必须偶尔“清除”成员列表。因此,考虑到上面的代码示例,这将是'tar.members = []'。更多信息在这里:http://bit.ly/JKXrg6 – devsnd 2012-05-21 17:45:51

9

您需要使用tarfile模块。具体而言,您使用类tar文件的实例与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(). 

访问该文件,然后访问的名称相反,如果你想阅读的内容,那么你用这个方法

| 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() 
+0

请注意,您可以通过像myFile = myArchive.extractfile(dict(myArchive.getnames(),myArchive.getmembers()))['path/to/file'])构造的索引访问成员。对于tar.getmembers()中的成员,read()' – ThorSummoner 2014-04-26 07:28:23

3

由@斯特凡诺 - 博里尼 提到的方法的实施方案通过文件名访问tar归档成员,像这样

#python3 
myFile = myArchive.extractfile( 
    dict(zip(
     myArchive.getnames(), 
     myArchive.getmembers() 
    ))['path/to/file'] 
).read()` 

现金

相关问题