0

I'm trying to interface with an existing library that uses the built in open() function to read a .json file using either a str or bytes object representing a path, or an object implementing the os.PathLike protocol.

My function generate a dictionary which is converted to json using json.dump(), but I'm not sure how to pass that to the existing function which expects a file path.

I was thinking something like this might work, but I'm not sure how to get a os.PathLike object of a TemporaryFile.

import tempfile
temp_file = tempfile.TemporaryFile('w')
json.dump('{"test": 1}', fp=temp_file)
file = open(temp_file.path(), 'r')
waspinator
  • 6,464
  • 11
  • 52
  • 78

1 Answers1

7

Create a NamedTemporaryFile() object instead; it has a .name attribute you can pass on to the function:

from tempfile import NamedTemporaryFile

with NamedTemporaryFile('w') as jsonfile:
    json.dump('{"test": 1}', jsonfile)
    jsonfile.flush()  # make sure all data is flushed to disk
    # pass the filename to something that expects a string
    open(jsonfile.name, 'r')

Opening an already-open file object does have issues on Windows (you are not allowed to); there you'd have to close the file object first (making sure to disable delete-on-close), and delete it manually afterwards:

from tempfile import NamedTemporaryFile
import os

jsonfile = NamedTemporaryFile('w', delete=False)
try:
    with jsonfile:
        json.dump('{"test": 1}', jsonfile)
    # pass the filename to something that expects a string
    open(jsonfile.name, 'r')
finally:
    os.unlink(jsonfile.name)

The with statement causes the file to be closed when the suite exits (so by the time you reach the open() call).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343