在python中将字节转换为文件对象 [英] Convert bytes to a file object in python

查看:184
本文介绍了在python中将字节转换为文件对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小型应用程序,该应用程序使用以下方式读取本地文件:
以csv_file的身份打开(diefile_path,'r')
打开(diefile_path,'r')作为文件
,并且还使用linecache模块

I have a small application that reads local files using:
open(diefile_path, 'r') as csv_file
open(diefile_path, 'r') as file
and also uses linecache module

我需要将其用途扩展到从远程服务器发送的文件.
服务器类型接收的内容是字节.

I need to expand the use to files that send from a remote server.
The content that is received by the server type is bytes.

我找不到很多有关处理IOBytes类型的信息,我想知道是否有一种方法可以将字节块转换为类似文件的对象.
我的目标是使用上面指定的API( open linecache )
我能够使用 data.decode("utf-8")
将字节转换为字符串但我不能使用上述方法( open linecache )

I couldn't find a lot of information about handling IOBytes type and I was wondering if there is a way that I can convert the bytes chunk to a file-like object.
My goal is to use the API is specified above (open,linecache)
I was able to convert the bytes into a string using data.decode("utf-8"),
but I can't use the methods above (open and linecache)

一个小例子来说明

data = 'b'First line\nSecond line\nThird line\n'

with open(data) as file:
    line = file.readline()
    print(line)

输出:

First line
Second line
Third line

能做到吗?

推荐答案

open 用于打开实际文件,并返回类似文件的对象.在这里,您已经将数据存储在内存中,而不是文件中,因此您可以直接实例化类似文件的对象.

open is used to open actual files, returning a file-like object. Here, you already have the data in memory, not in a file, so you can instantiate the file-like object directly.

import io


data = b'First line\nSecond line\nThird line\n'
file = io.StringIO(data.decode())
for line in file:
    print(line.strip())

但是,如果您得到的实际上只是换行符分隔的字符串,则可以直接将其直接分成列表.

However, if what you are getting is really just a newline-separated string, you can simply split it into a list directly.

lines = data.decode().strip().split('\n')

主要区别在于 StringIO 版本略显懒惰;与列表相比,它的内存占用量较小,因为它可以按照迭代器的要求拆分字符串.

The main difference is that the StringIO version is slightly lazier; it has a smaller memory foot print compared to the list, as it splits strings off as requested by the iterator.

这篇关于在python中将字节转换为文件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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