Python:tarfile流 [英] Python: tarfile stream

查看:116
本文介绍了Python:tarfile流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从压缩包中读取一些文件并将其保存到新的压缩包中. 这是我写的代码.

I would like to read some files from a tarball and save it to a new tarball. This is the code I wrote.

archive = 'dum/2164/archive.tar'

# Read input data.
input_tar = tarfile.open(archive, 'r|')
tarinfo = input_tar.next()
input_tar.close()

# Write output file.
output_tar = tarfile.open('foo.tar', 'w|')
output_tar.addfile(tarinfo)
output_tar.close()

不幸的是,输出的tarball不好:

Unfortunately, the output tarball is no good:

$ tar tf foo.tar
./1QZP_A--2JED_A--not_reformatted.dat.bz2
tar: Truncated input file (needed 1548288 bytes, only 1545728 available)
tar: Error exit delayed from previous errors.

有任何线索如何使用Python即时读写tarball吗?

Any clue how to read and write tarballs on the fly with Python?

推荐答案

好的,这就是我设法做到的方式.

OK so this is how I managed to do it.

archive = 'dum/2164/archive.tar'

# Read input data.
input_tar = tarfile.open(archive, 'r|')
tarinfo = input_tar.next()
fileobj = input_tar.extractfile(tarinfo)

# Write output file.
output_tar = tarfile.open('foo.tar', 'w|')
output_tar.addfile(tarinfo, fileobj)

input_tar.close()
output_tar.close()

这篇关于Python:tarfile流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆