加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何从Python中读取损坏的tar.bz2文件?

发布时间:2020-12-20 13:26:51 所属栏目:Python 来源:网络整理
导读:我有一个程序,它的输出保存到tar.bz2文件,因为它的工作原理.我有一个处理该数据的 python脚本. 如果第一个程序被中断,我希望能够使用输出 – 或者只是在进程正在进行时对它运行python脚本. 当然,最终的bzip2块未完成,因此无法读取 – 它实际上已被破坏,尽管
我有一个程序,它的输出保存到tar.bz2文件,因为它的工作原理.我有一个处理该数据的 python脚本.

如果第一个程序被中断,我希望能够使用输出 – 或者只是在进程正在进行时对它运行python脚本.

当然,最终的bzip2块未完成,因此无法读取 – 它实际上已被破坏,尽管实际上它只是被截断了. GNU tar实际上很乐意提取文件到目前为止的所有功能 – 就像bzcat一样.并且bzip2recover可以创建修复的块,尽管在这种情况下它比bzcat更有用.

但我正在尝试使用Python的标准tarfile模块.这失败了

File "/usr/lib64/python2.7/tarfile.py",line 2110,in extractfile
    tarinfo = self.getmember(member)
  File "/usr/lib64/python2.7/tarfile.py",line 1792,in getmember
    tarinfo = self._getmember(name)
  File "/usr/lib64/python2.7/tarfile.py",line 2361,in _getmember
    members = self.getmembers()
  File "/usr/lib64/python2.7/tarfile.py",line 1803,in getmembers
    self._load()        # all members,we first have to
  File "/usr/lib64/python2.7/tarfile.py",line 2384,in _load
    tarinfo = self.next()
  File "/usr/lib64/python2.7/tarfile.py",line 2319,in next
    self.fileobj.seek(self.offset)
EOFError: compressed file ended before the logical end-of-stream was detected

当我尝试在我知道的文件开头使用TarFile.extract文件时. (tar -xf tarfile.tar.bz2文件名将提取它就好了.)

有什么聪明的我可以做的事情来忽略文件的无效结束并使用我所拥有的东西吗?

数据集可以变得相当大,并且非常非常可压缩,因此保持其未压缩是不可取的.

(我找到了现有的问题Untar archive in Python with errors,但在这种情况下,用户正在尝试os.system tar文件.)

解决方法

似乎有两种可能性.首先,最有可能的是:

If ignore_zeros is False,treat an empty block as the end of the
archive. If it is True,skip empty (and invalid) blocks and try to get
as many members as possible. This is only useful for reading
concatenated or damaged archives.

其次:

For special purposes,there is a second format for mode: ‘filemode|[compression]’. tarfile.open() will return a TarFile object that processes its data as a stream of blocks. No random seeking will be done on the file. If given,fileobj may be any object that has a read() or write() method (depending on the mode). bufsize specifies the blocksize and defaults to 20 * 512 bytes. Use this variant in combination with e.g. sys.stdin,a socket file object or a tape device. However,such a TarFile object is limited in that it does not allow to be accessed randomly

当文件不完整时,听起来像访问文件可能很有用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读