我正在尝试从大tar文件中提取我感兴趣的特定文件夹。
import tarfile
import os
list_dir = []
models = ["usb","test"]
with tarfile.open("build_today.tar.gz") as tar:
for tarinfo in tar.getmembers():
if tarinfo.name.startswith(os.path.join("build_today","pips")):
for model in models:
if tarinfo.name.startswith(os.path.join("build_today","pips",model,"")):
list_dir.append(tarinfo.name)
elif tarinfo.name.startswith(os.path.join("build_today","objects")):
for model in models:
if tarinfo.name.startswith(os.path.join("build_today","objects",model,"")):
list_dir.append(tarinfo.name)
else:
list_dir.append(tarinfo.name)
print list_dir
tar.extractall(members=list_dir)
我能够打印'list_dir',在这里我可以看到期望的内容。但是提取时失败。
失败,并显示错误:
Traceback (most recent call last):
File "tar.py", line 18, in <module>
tar.extractall(members=list_dir)
File "/grid/common/pkgs/python/v2.7.10/lib/python2.7/tarfile.py", line 2067, in extractall
if tarinfo.isdir():
AttributeError: 'str' object has no attribute 'isdir'
请帮助!
答案 0 :(得分:1)
从初步分析来看,问题似乎出在这里:
list_dir.append(tarinfo.name)
在这里,您将文件名附加为字符串。相反,您需要具有.isdir()
内置方法