【问题标题】:get the size in bytes of a StringIO object获取 StringIO 对象的字节大小
【发布时间】:2017-09-18 04:40:00
【问题描述】:

是否可以获取 StringIO 对象的字节大小?还是每次我想获得它的大小时都应该将它写入磁盘?
我搜索了很多但没有成功。 .sizeof() 但我认为这不是我想要的。

我正在遍历文件名列表

temp=StringIO()
for idx,filename in enumerate(filenames):
    temp.write('something')
    if ((temp.__sizeof__()+os.path.getsize(os.path.join(inputf,filenames[idx])))/1048576.0 >= 128.0):
        (do something)

【问题讨论】:

    标签: python-2.7 stringio cstringio


    【解决方案1】:

    你应该寻找到最后并使用tell()

    temp.write('something')
    temp.seek(0, os.SEEK_END)
    if ((temp.tell()+...
    

    例子:

    from StringIO import StringIO
    import os
    temp = StringIO()
    temp.write("abc€")
    temp.seek(0, os.SEEK_END)
    print temp.tell() #6
    

    【讨论】:

    • 我认为 .tell() 会给我 temp 中的元素数量。我会有 temp 的大小(以字节为单位),就像您使用 os.path.getsize(file) 时一样
    • 我会接受你的回答,因为它回答了我的问题,但是使用 seek() 会从头开始倒回 temp,因为我正在连接 XML 文件,并且只有在以下情况下我才会将我的临时文件写入磁盘它有一定的大小。我担心使用 seek 时,它每次都会重置我的温度,我将永远无法通过 if 语句。
    • 这取决于你如何构建你的循环
    猜你喜欢
    • 2017-12-18
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多