Treat a string as a file in python

前端 未结 4 1885
傲寒
傲寒 2021-01-04 10:45

In the interest of not rewriting an open source library, I want to treat a string of text as a file in python 3.

Suppose I have the file contents as a stri

4条回答
  •  我在风中等你
    2021-01-04 11:23

    the other answers didn't work for me, but I managed to figure it out.

    When using Python 3, you'll want to use io package.

        import io
        with io.StringIO("some initial text data") as f:
            # now you can do things with f as if it was an opened file.
            function_that_requires_a_Fileobject_as_argument(f)
    

提交回复
热议问题