Treat a string as a file in python

前端 未结 4 1848
傲寒
傲寒 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:41

    StringIO returns an StringIO object, it's almost equivalent to the file object returned by the open statement. So basically, you can use the StringIO in place of the open statement.

    # from io import StringIO for python 3
    from StringIO import StringIO
    with StringIO('there is a lot of blah blah in this so-called file') as f:
        print(f.read())
    

    Output:

    there is a lot of blah blah in this so-called file
    

提交回复
热议问题