python python类文件缓冲对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1368261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python file-like buffer object
提问by djs
I've written a buffer class that provides a File-like interface with read
, write
, seek
, tell
, flush
methods to a simple string in memory. Of course it is incomplete (e.g. I didn't write readline
). It's purpose is to be filled by a background thread from some external data source, but let a user treat it like a file. I'd expect it to contain a relatively small amount of data (maybe 50K max)
我编写了一个缓冲区类,它提供了一个类似文件的接口,其中包含read
, write
, seek
, tell
,flush
方法到内存中的一个简单字符串。当然它是不完整的(例如我没有写readline
)。它的目的是由来自某些外部数据源的后台线程填充,但让用户将其视为文件。我希望它包含相对少量的数据(最大可能是 50K)
Is there a better way to do this instead of writing it from scratch?
有没有更好的方法来做到这一点而不是从头开始编写?
回答by Triptych
You can use the standard Python modules StringIO
or cStringIO
to obtain an in-memory buffer which implements the file interface.
您可以使用标准 Python 模块StringIO
或cStringIO
获取实现文件接口的内存缓冲区。
cStringIO
is implemented in C, and will be faster, so you should use that version if possible.
cStringIO
是用 C 实现的,速度会更快,所以你应该尽可能使用那个版本。
If you're using Python 3 you should use the io.StringIO
instead of StringIO
and io.BytesIO
instead of cStringIO
.
如果您使用的是 Python 3,则应使用io.StringIO
代替StringIO
和io.BytesIO
代替cStringIO
。
回答by Randy Morris
I think you might be looking for StringIO
.
我想你可能正在寻找StringIO
.