StringIO and compatibility with 'with' statement (context manager)

前端 未结 3 602
无人共我
无人共我 2020-12-23 16:41

I have some legacy code with a legacy function that takes a filename as an argument and processes the file contents. A working facsimile of the code is below.

What

3条回答
  •  春和景丽
    2020-12-23 17:00

    This one is based on the python doc of contextmanager

    It's just wrapping StringIO with simple context, and when exit is called, it will return to the yield point, and properly close the StringIO. This avoids the need of making tempfile, but with large string, this will still eat up the memory, since StringIO buffer that string. It works well on most cases where you know the string data is not going to be long

    from contextlib import contextmanager
    
    @contextmanager
    def buildStringIO(strData):
        from cStringIO import StringIO
        try:
            fi = StringIO(strData)
            yield fi
        finally:
            fi.close()
    

    Then you can do:

    with buildStringIO('foobar') as f:
        print(f.read()) # will print 'foobar'
    

提交回复
热议问题