Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 访问.tar文件中的.tar文件_Python_Tar - Fatal编程技术网

Python 访问.tar文件中的.tar文件

Python 访问.tar文件中的.tar文件,python,tar,Python,Tar,我有一个焦油档案,其中包含一些其他焦油档案。下面的示例完美地提取了primary.tar文件,但在获取其中的其他.tar文件时遇到了问题 import tarfile import os fd = tarfile.open('test.tar') for member in fd.getmembers(): if not member.isfile(): continue cfile = fd.extractfile(member) name = cf

我有一个焦油档案,其中包含一些其他焦油档案。下面的示例完美地提取了primary.tar文件,但在获取其中的其他.tar文件时遇到了问题

import tarfile
import os

fd = tarfile.open('test.tar')
for member in fd.getmembers():
    if not member.isfile():
        continue

    cfile = fd.extractfile(member)
    name = cfile.name
    filename, file_extension = os.path.splitext(name)
    #print filename + "----" + file_extension

    if file_extension == ".tar":
        print cfile
    #print cfile.read()
    print cfile.name
    cfile.close()
fd.close()
这将返回以下内容:

file1.txt
file2.txt
<tarfile.ExFileObject object at 0x101989690>
tar1.tar
file1.txt
file2.txt
焦油

所以我可以访问tar1.tar文件对象。但是,我无法确定如何从tar1.tar获取成员或内容。

cfile
作为
fileobj
参数传递给对
tarfile.open()的新调用

测试:

$touch a b c x y z
$tar cf y.tar x y z
$tar cf x.tar a b y.tar c
$python t.py
A.
B
y、 焦油
x
Y
Z
C

。。。与对主tar文件执行此操作的方式相同?是的,我尝试过,但是
getmembers()
tarfile.ExFileObject
object不存在。您可以尝试递归执行此操作,但我不知道是否可以先提取它。你用的是python2还是pytho3?如果你允许我访问你拥有的文件,我可以试一试并发布代码。非常感谢如果我想根据每个文件的路径/名称选择获取每个文件的内容,有没有办法做到这一点?我相信您可以添加代码来实现这一点。试试看。如果你被卡住了,你可以随时问另一个问题!
import tarfile
import os

def list_contents(name, fileobj=None, prefix=''):
    fd = tarfile.open(name, fileobj=fileobj)
    for member in fd.getmembers():
        if not member.isfile():
            continue
        cfile = fd.extractfile(member)
        name = cfile.name
        filename, file_extension = os.path.splitext(name)
        print prefix + cfile.name
        if file_extension == '.tar':
            list_contents(name, cfile, prefix+'    ')
        cfile.close()
    fd.close

list_contents('x.tar')