Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.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 tarfile不';不适用于.gz文件_Python_Tarfile - Fatal编程技术网

Python tarfile不';不适用于.gz文件

Python tarfile不';不适用于.gz文件,python,tarfile,Python,Tarfile,我有一个嵌套的tarfile,格式为 tarfile.tar.gz --tar1.gz --tar1.txt --tar2.gz --tar3.gz 我想用python编写一个小脚本,将所有tar首先提取到相同的文件夹顺序中,即tar1.txt应该位于tarfile/tar1中/ 这是剧本 #!/usr/bin/python import os import re import tarfile data = os.path.join(os.getcwd(), 'data') dirs

我有一个嵌套的tarfile,格式为

tarfile.tar.gz
--tar1.gz
  --tar1.txt
--tar2.gz
--tar3.gz
我想用python编写一个小脚本,将所有tar首先提取到相同的文件夹顺序中,即tar1.txt应该位于tarfile/tar1中/

这是剧本

#!/usr/bin/python

import os
import re
import tarfile

data = os.path.join(os.getcwd(), 'data')
dirs = [data]

while len(dirs):
    dirpath = dirs.pop(0)
    for subpath in os.listdir(dirpath):
        if not re.search('(.tar)?.gz$', subpath):
            continue
        with tarfile.open(os.path.join(dirpath, subpath)) as tarf:
            tarf.extractall(path=dirpath)
    for subpath in os.listdir(dirpath):
        newpath = os.path.join(dirpath, subpath)
        if os.path.isdir(newpath):
            dirs.append(newpath)
        elif dirpath != data or os.path.islink(newpath):
            os.remove(newpath)
但是,当我运行脚本时,会出现以下错误:

Traceback (most recent call last):
  File "./extract.py", line 16, in <module>
    with tarfile.open(os.path.join(dirpath, subpath)) as tarf:
  File "/usr/lib/python2.7/tarfile.py", line 1678, in open
    raise ReadError("file could not be opened successfully")
tarfile.ReadError: file could not be opened successfully
回溯(最近一次呼叫最后一次):
文件“/extract.py”,第16行,在
使用tarfile.open(os.path.join(dirpath,subpath))作为tarf:
文件“/usr/lib/python2.7/tarfile.py”,第1678行,打开
raise ReadError(“文件无法成功打开”)
tarfile.ReadError:无法成功打开文件

可以很好地提取“.tar.gz”文件,但不能提取嵌套的“.gz”文件。上面是什么?tarfile模块不处理.gz文件吗

.gz表示该文件是gzip。tar.gz表示已gzip的tar文件
tarfile
可以很好地处理gzip压缩的tar,但它不能处理非tar存档的文件(如tar1.gz)。

low,处理
.tar.gz
只是一种方便。如果要读取gzip文件,必须使用
gzip
模块。