如何解决为什么提取功能停止提取?
| 有人可以解释并帮助我解决为什么我添加计数器创建名称不同的文件夹时,我的函数停止提取.tgz文件的原因,以防止当我提取同一目录中的另一个.tgz文件时,提取的文件夹不会覆盖先前的文件夹吗?我究竟做错了什么?谢谢!以下是两个函数...第一个函数正确提取文件;第二个函数提取一个编号的文件夹并退出。 作品: def extract(tar_url,extract_path=\'.\'):
print tar_url
tar = tarfile.open(tar_url,\'r\')
for item in tar:
tar.extract(item,extract_path)
if item.name.find(\".tgz\") != -1 or item.name.find(\".tar\") != -1:
extract(item.name,\"./\" + item.name[:item.name.rfind(\'/\')])
不起作用:
global counter
counter=1
def extract(tar_url,extract_path=\'.\'):
global counter
print tar_url
tar = tarfile.open(tar_url,\'wb\')# changed from r to wb 6/12
for item in tar:
tar.extract(item,extract_path+\"_%d\"%counter)
counter+=1
if item.name.find(\".tgz\") != -1 or item.name.find(\".tar\") != -1:
extract(item.name,\"./\" + item.name[:item.name.rfind(\'/\')])
这是我在main中使用的方式(我正在使用easygui):
direct = diropenbox(msg=\"Choose path to place extracted files!\",title=\'SQA Extractor\',default=\'c:\\\\Extracted\')
msg = \"Are you sure you want to extract?\"
title = \"Confirm\"
os.chdir(direct)
try:
for root,dirname,files in os.walk(directory):
for file1 in files:
if file1.endswith(\".tgz\") or file1.endswith(\".tar\"):
extract(os.path.join(root,file1))
解决方法
也许正是这种更改破坏了您的代码:
tar = tarfile.open(tar_url,\'r\')
变成:
tar = tarfile.open(tar_url,\'wb\')# changed from r to wb 6/12
, 是否存在带有计数器的提取路径?
for item in tar:
os.mkdir(extract_path + \"_%d\" % counter)
tar.extract(item,extract_path+\"_%d\" % counter)
counter+=1
if item.name.find(\".tgz\") != -1 or item.name.find(\".tar\") != -1:
extract(item.name,\"./\" + item.name[:item.name.rfind(\'/\')])
, 原始版本依赖于创建的文件夹名称,该名称与存档中指定的相对路径匹配。在新版本中,递归调用会尝试将文件提取到一个没有\'tag \'编号的文件夹中,然后再将该级别的其他文件提取到一个文件夹中。
也尝试将标记添加到用于递归调用的路径名中。
顺便说一句,Python惯用的Python6拼写是\'.tar\' in item.name
。