python - 如何使用 io 在内存中生成数据流作为文件之类的对象?

标签 python file io temporary-files

我喜欢用 Python 生成内存中(临时文件)数据流。一个线程用数据填充流,另一个线程使用数据。

检查 io - Core tools for working with streams 后, 在我看来 io 模块是它的最佳选择。

所以我举个简单的例子给我:

#!/usr/local/bin/python3
# encoding: utf-8

import io

if __name__ == '__main__':
    a = io.BytesIO()
    a.write("hello".encode())
    txt = a.read(100)
    txt = txt.decode("utf-8")
    print(txt) 

我的示例不起作用。 "hello" 没有写入a,之后无法读取。那是我的错误吗?我必须如何更改我的代码才能在内存中获取类似对象的文件?

最佳答案

其实是这样写的;但阅读是个问题。你应该指的是class io.BytesIO .您可以使用 getvalue() 获取值。喜欢,

import io

a = io.BytesIO()
a.write("hello".encode())
txt = a.getvalue()
txt = txt.decode("utf-8")
print(txt) 

关于python - 如何使用 io 在内存中生成数据流作为文件之类的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52183096/

相关文章:

.NET Core 2.0 ASP.NET MVC 下载文件和调用文件保存对话框

c - 如何使用 fscanf 解析 csv 文件?

c - getch() 和 getchar() 有什么区别?

parsing - Haskell:如何将 IO 输入字符串解析为 Float(或 Int 或其他)?

python - 相当于基本 python 中的 Numpy.argsort()?

python - 使用字典值过滤数据帧,同时将字典键分配给匹配的行?

python - 在python中使用基类classmethod实例化派生类对象

python - 从查询集中获取查询集

C#将文本添加到文本文件而不重写它?

c - 读入十六进制值 (C)