Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

And get the bytes of that StringIO object?

like image 704
TIMEX Avatar asked Jan 13 '11 06:01

TIMEX


People also ask

What is a StringIO object?

The StringIO module is an in-memory file-like object. This object can be used as input or output to the most function that would expect a standard file object. When the StringIO object is created it is initialized by passing a string to the constructor. If no string is passed the StringIO will start empty.


Video Answer


2 Answers

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

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 any file-like object.

like image 199
Glenn Maynard Avatar answered Sep 24 '22 01:09

Glenn Maynard


By checking the len attribute and using the getvalue() method

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' 
like image 28
Kimvais Avatar answered Sep 25 '22 01:09

Kimvais