Python--best way to use "open" command with in-memory str

Viewed 146

I have a library I need to call that takes a local file path as input and runs open(local_path, 'rb'). However, I don't have a local file--I have an in memory text string. Right now I am writing that to a temp file and passing that, but it seems wasteful. Is there a better way to do this, given that I need to be able to run open(local_path, 'rb') on it?

Current code:

    text = "Some text"

    temp = tempfile.TemporaryFile(delete=False)
    temp.write(bytes(text, 'UTF-8'))
    temp.seek(0)
    temp.close()
    
    #call external lib here, passing in temp.name as the local_path input

Later, inside the lib I need to use (I can't edit this):

    with open(local_path, 'rb') as content_file:
            file_content = content_file.read()
1 Answers

Since the function you call in turn calls open() with the passed parameter, you must give it a str or a PathLike. This means you basically need a file which exists in the file system. You won't be able to pass an in-memory object like I was originally thinking.

Original answer:

I suggest looking at the io package. Specifically, StringIO provides a file-like wrapper on an in-memory string object. If you need binary, then try BytesIO.

Related