python tar文件如何将文件提取到流中 [英] python tar file how to extract file into stream

查看:74
本文介绍了python tar文件如何将文件提取到流中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提取一个压缩文件夹,但不是直接使用 .extractall(),我想将文件提取到流中,以便我可以自己处理流.是否可以使用 tarfile 来实现?或者有什么建议?

I am trying to extract a zipped folder but instead of directly using .extractall(), I want to extract the file into stream so that I can handle the stream myself. Is it possible to do it using tarfile? Or is there any suggestions?

推荐答案

您可以使用 .extractfile()file 对象> 方法.循环遍历 tarfile.TarFile() 实例以列出所有条目:

You can obtain each file from a tar file as a python file object using the .extractfile() method. Loop over the tarfile.TarFile() instance to list all entries:

import tarfile

with tarfile.open(path) as tf:
    for entry in tf:  # list each entry one by one
        fileobj = tf.extractfile(entry)
        # fileobj is now an open file object. Use `.read()` to get the data.
        # alternatively, loop over `fileobj` to read it line by line.

这篇关于python tar文件如何将文件提取到流中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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