tarfile 不适用于 .gz 文件
tarfile doesn't work for .gz files
我有一个
形式的嵌套 tarfile
tarfile.tar.gz
--tar1.gz
--tar1.txt
--tar2.gz
--tar3.gz
我想在 python 中编写一个小脚本,以首先将所有 tars 广度提取到相同顺序的文件夹中,即 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
“.tar.gz”文件提取正常,但不是嵌套的“.gz”文件。这里有什么? tarfile 模块不处理 .gz 文件吗?
.gz 表示文件被gzip压缩; .tar.gz 表示已压缩的 tar 文件。 tarfile
可以很好地处理 gzipped tars,但它不能处理非 tar 存档的文件(比如你的 tar1.gz)。
我有一个
形式的嵌套 tarfiletarfile.tar.gz
--tar1.gz
--tar1.txt
--tar2.gz
--tar3.gz
我想在 python 中编写一个小脚本,以首先将所有 tars 广度提取到相同顺序的文件夹中,即 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
“.tar.gz”文件提取正常,但不是嵌套的“.gz”文件。这里有什么? tarfile 模块不处理 .gz 文件吗?
.gz 表示文件被gzip压缩; .tar.gz 表示已压缩的 tar 文件。 tarfile
可以很好地处理 gzipped tars,但它不能处理非 tar 存档的文件(比如你的 tar1.gz)。