在python中将字节转换为文件对象

Ita*_*arG 4 python string file bytestream

我有一个小应用程序,它使用以下方式读取本地文件:
open(diefile_path, 'r') as csv_file
open(diefile_path, 'r') as file
and also uses linecache module

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

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

一个小例子来说明

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

with open(data) as file:
    line = file.readline()
    print(line)
Run Code Online (Sandbox Code Playgroud)

输出:

First line
Second line
Third line
Run Code Online (Sandbox Code Playgroud)

可以吗?

che*_*ner 5

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

import io


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

但是,如果您得到的实际上只是一个换行符分隔的字符串,您可以直接将其拆分为一个列表。

lines = data.decode().strip().split('\n')
Run Code Online (Sandbox Code Playgroud)

主要区别是StringIO版本稍微懒一些;与列表相比,它的内存占用更小,因为它按照迭代器的要求分割字符串。


Aob*_*a K 5

上面的答案使用StringIO需要指定编码,这可能会导致错误的转换。

来自Python 文档,使用BytesIO

from io import BytesIO
f = BytesIO(b"some initial binary data: \x00\x01")
Run Code Online (Sandbox Code Playgroud)