我喜欢用 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/