Treat a string as a file in python

前端 未结 4 1849
傲寒
傲寒 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
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题