GZip:Python - 如何使用gzip.open获取特定行的文件名

时间:2016-02-06 07:31:23

标签: python python-2.7 gzip

我有一个'.tgz'文件,我正在使用gzip.open读取'.tgz'文件的内容。获取特定行的文件名的最快方法是什么?

with gzip.open('sample.tgz','r') as fin:
    for line in fin:
        error = checkForError(line)
        if error:
            # get the file name in which that particular error line was present
        else:
            pass

1 个答案:

答案 0 :(得分:0)

这个功能,但它是多么有用,是任何人的猜测 检查https://en.wikipedia.org/wiki/Tar_%28computing%29#Header是否有标题格式。

import gzip
fin = gzip.open("test.txt.tar","r")
for i in fin:
    if "ustar" in i:
        fname,b = i.split("0",1)
        print fname
    else:
        print i
fin.close()

注意:这是针对Linux上的python 2.7.6,假设存档是使用tar czvf创建的