58

And get the bytes of that StringIO object?

0

3 Answers 3

85

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I recommend storing the result of pos = s.tell() and s.seek(pos) after checking this value, in the case that file position is important to any of your consumers.
22

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'

7 Comments

I don't have that. Instead, I have this: ['class', 'delattr', 'doc', 'format', 'getattribute', 'hash', 'init', 'iter', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'close', 'closed', 'flush', 'getvalue', 'isatty', 'next', 'read', 'readline', 'readlines', 'reset', 'seek', 'tell', 'truncate']
I'm guessing you're actually using cStringIO and not StringIO, which--for what reason I don't know--doesn't have a len property to match StringIO. I guess the len property is actually undocumented, which is also a little odd.
Also note that the len was removed in Python3, so you cannot use your solution in Python3.
When on Python3, please note that StringIO.write() returns the amount of characters written, so you can just keep track of them without the need of checking the length...
This does not work in Python 3.5. AttributeError: '_io.StringIO' object has no attribute 'len'
|
0

I used the 'getvalue' method and checked the length of the return value

len(s.getvalue())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.