我有一堆文件,需要进行以下处理:

for file_name in filelist:
  tar_file = tarfile.open(file_name)
  tar_file.extractall("./" + "location")


对于特定文件,在tarfile.open调用后我立即收到此错误:

$ file file_name.tgz
file_name.tgz: gzip compressed data, from Unix, last modified: Mon Dec 16 16:33:34 2013


追溯(最近一次通话):

  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/tarfile.py", line 1660, in open
    return func(name, "r", fileobj, **kwargs)
  File "/usr/lib/python2.7/tarfile.py", line 1727, in gzopen
    **kwargs)
  File "/usr/lib/python2.7/tarfile.py", line 1705, in taropen
    return cls(name, mode, fileobj, **kwargs)
  File "/usr/lib/python2.7/tarfile.py", line 1574, in __init__
    self.firstmember = self.next()
  File "/usr/lib/python2.7/tarfile.py", line 2319, in next
    tarinfo = self.tarinfo.fromtarfile(self)
  File "/usr/lib/python2.7/tarfile.py", line 1239, in fromtarfile
    buf = tarfile.fileobj.read(BLOCKSIZE)
  File "/usr/lib/python2.7/gzip.py", line 256, in read
    self._read(readsize)
  File "/usr/lib/python2.7/gzip.py", line 320, in _read
    self._read_eof()
  File "/usr/lib/python2.7/gzip.py", line 339, in _read_eof
    isize = read32(self.fileobj)  # may exceed 2GB
  File "/usr/lib/python2.7/gzip.py", line 25, in read32
    return struct.unpack("<I", input.read(4))[0]
struct.error: unpack requires a string argument of length 4


问题:如何避免这种情况?

最佳答案

您需要一些异常处理:

for file_name in filelist:
    try:
        tar_file = tarfile.open(file_name)
        tar_file.extractall("./" + "location")
    except struct.error, e:  # or except struct.error as e, depends on Python version
        print "Corrupt:", file_name
    except tarfile.TarError, e:
        print "Tar error (%s): %s" % (str(e), file_name)


这样,您就可以看到错误并记录下来,但是请继续进行下去。

http://docs.python.org/2.7/library/tarfile.html记录了tarfile模块中的异常。

关于python - python tarfile错误:struct.error:解压缩需要长度为4的字符串参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20646551/

10-12 22:42