Binary buffer in Python

后端 未结 3 1378
悲&欢浪女
悲&欢浪女 2020-12-02 15:27

In Python you can use StringIO for a file-like buffer for character data. Memory-mapped file basically does similar thing for binary data, but it requires a file that is use

3条回答
  •  不思量自难忘°
    2020-12-02 16:07

    As long as you don't try to put any unicode data into your StringIO and you are careful NOT to use cStringIO you should be fine.

    According to the StringIO documentation, as long as you keep to either unicode or 8-bits everything works as expected. Presumably, StringIO does something special when someone does a f.write(u"asdf") (which ZipFile does not do, to my knowledge). Anyway;

    import zipfile
    import StringIO
    
    s = StringIO.StringIO()
    z = zipfile.ZipFile(s, "w")
    z.write("test.txt")
    z.close()
    f = file("x.zip", "w")
    f.write(s.getvalue())
    s.close()
    f.close()
    

    works just as expected, and there's no difference between the file in the resulting archive and the original file.

    If you know of a particular case where this approach does not work, I'd be most interested to hear about it :)

提交回复
热议问题