在 Python 中,如何检查 StringIO 对象的大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4677433/
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-08-18 16:54:10  来源:igfitidea点击:

In Python, how do I check the size of a StringIO object?

python

提问by TIMEX

And get the bytes of that StringIO object?

并获取该 StringIO 对象的字节?

采纳答案by Glenn Maynard

StringIOobjects implement the file API, so you can get their size in exactly the same way as you can with a fileobject: seek to the end and see where it goes.

StringIO对象实现了文件 API,因此您可以以与使用file对象完全相同的方式获取它们的大小:寻找到最后并查看它的去向。

from StringIO import StringIO
import os
s = StringIO()
s.write("abc")
pos = s.tell()
s.seek(0, os.SEEK_END)
print s.tell()
s.seek(pos)

As Kimvais mentions, you can also use the len, but note that that's specific to StringIO objects. In general, a major reason to use these objects in the first place is to use them with code that expects a file-like object. When you're dealing with a generic file-like object, you generally want to do the above to get its length, since that works with anyfile-like object.

正如 Kimvais 所提到的,您也可以使用len,但请注意,这是特定于 StringIO 对象的。通常,首先使用这些对象的一个​​主要原因是将它们与需要类文件对象的代码一起使用。当您处理一个通用的类文件对象时,您通常希望执行上述操作以获取其长度,因为这适用于任何类文件对象。

回答by Kimvais

By checking the lenattribute and using the getvalue()method

通过检查len属性并使用getvalue()方法

Type "help", "copyright", "credits" or "license" for more information.
>>> import StringIO
>>> s = StringIO.StringIO()
>>> s.write("foobar")
>>> s.len
6
>>> s.write(" and spameggs")
>>> s.len
19
>>> s.getvalue()
'foobar and spameggs'