我正在尝试编写一个python程序,最终将获取文件的命令行参数,确定它是否是tar或zip等文件,然后相应地对其进行exctract.我只是试图让tar部分工作,我得到了多个错误.我正在检查的文件位于我的〜/目录中.任何想法都会很棒.
#!/usr/bin/python
import tarfile
import os
def open_tar(file):
if tarfile.is_tarfile(file):
try:
tar = tarfile.open("file")
tar.extractall()
tar.close()
except ReadError:
print "File is somehow invalid or can not be handled by tarfile"
except CompressionError:
print "Compression method is not supported or data cannot be decoded"
except StreamError:
print "Is raised for the limitations that are typical for stream-like TarFile objects."
except ExtractError:
print "Is raised for non-fatal errors when using TarFile.extract(), but only if TarFile.errorlevel== 2."
if __name__ == '__main__':
file = "xampp-linux-1.7.3a.tar.gz"
print os.getcwd()
print file
open_tar(file)
Run Code Online (Sandbox Code Playgroud)
这是错误.如果我注释掉读错误,我也会在下一个异常中得到同样的错误.
tux@crosnet:~$ python openall.py
/home/tux
xampp-linux-1.7.3a.tar.gz
Traceback (most recent call last):
File "openall.py", line 25, in <module>
open_tar(file)
File "openall.py", line 12, in open_tar
except ReadError:
NameError: global name 'ReadError' is not defined
tux@crosnet:~$
Run Code Online (Sandbox Code Playgroud)
Bar*_*tek 10
你可以清楚地看到你的错误
NameError: global name 'ReadError' is not defined
Run Code Online (Sandbox Code Playgroud)
ReadError不是全局python名称.如果查看tarfile文档,您会看到ReadError是该模块异常的一部分.所以在这种情况下,你会想做:
except tarfile.ReadError:
# rest of your code
Run Code Online (Sandbox Code Playgroud)
而且你需要对其余的错误做同样的事情.此外,如果所有这些错误都会产生相同的结果(某种错误消息或传递),您可以简单地执行以下操作:
except (tarfile.ReadError, tarfile.StreamError) # and so on
Run Code Online (Sandbox Code Playgroud)
而不是分别在单独的线上做它们.只有他们会给出相同的例外情况