Treat a string as a file in python

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

    With what I can tell from your comments and recent edits, you want a file that can be opened using the open statement. (I'll leave my other answer be since it's the more correct approach to this type of question)

    You can use tempfile to solve your problem, it basically is doing this: create your file, do stuff to your file, then delete your file upon closure.

    import os
    from tempfile import NamedTemporaryFile
    
    f = NamedTemporaryFile(mode='w+', delete=False)
    f.write("there is a lot of blah blah in this so-called file")
    f.close()
    with open(f.name, "r") as new_f:
        print(new_f.read())
    
    os.unlink(f.name) # delete the file after
    

提交回复
热议问题