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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:04:22  来源:igfitidea点击:

python file-like buffer object

pythoniobuffer

提问by djs

I've written a buffer class that provides a File-like interface with read, write, seek, tell, flushmethods 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 StringIOor cStringIOto obtain an in-memory buffer which implements the file interface.

您可以使用标准 Python 模块StringIOcStringIO获取实现文件接口的内存缓冲区。

cStringIOis 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.StringIOinstead of StringIOand io.BytesIOinstead of cStringIO.

如果您使用的是 Python 3,则应使用io.StringIO代替StringIOio.BytesIO代替cStringIO

回答by Randy Morris

I think you might be looking for StringIO.

我想你可能正在寻找StringIO.