Treat a string as a file in python

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

    You can create a temporary file and pass its name to open:

    On Unix:

    tp = tempfile.NamedTemporaryFile()
    tp.write(b'there is a lot of blah blah blah in this so-called file')
    tp.flush()
    open(tp.name, 'r')
    

    On Windows, you need to close the temporary file before it can be opened:

    tp = tempfile.NamedTemporaryFile(delete=False)
    tp.write(b'there is a lot of blah blah blah in this so-called file')
    tp.close()
    open(tp.name, 'r')
    

    You then become responsible for deleting the file once you're done using it.

提交回复
热议问题