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

前端 未结 2 1089
生来不讨喜
生来不讨喜 2021-01-31 13:56

And get the bytes of that StringIO object?

2条回答
  •  死守一世寂寞
    2021-01-31 14:53

    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.

提交回复
热议问题