2010-01-07 200 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()` 

現金

相關問題