Python 使用Open()打开临时文件

Python 使用Open()打开临时文件,python,python-3.x,Python,Python 3.x,我正在尝试与现有库接口,该库使用内置函数读取.json文件 我的函数生成一个字典,该字典使用json.dump()转换为json,但我不确定如何将其传递给需要文件路径的现有函数 我在想这样的东西可能会有用,但我不确定如何获得一个临时文件的os.PathLike对象 import tempfile temp_file = tempfile.TemporaryFile('w') json.dump('{"test": 1}', fp=temp_file) file = open(temp_file.

我正在尝试与现有库接口,该库使用内置函数读取
.json
文件

我的函数生成一个字典,该字典使用
json.dump()
转换为
json
,但我不确定如何将其传递给需要文件路径的现有函数

我在想这样的东西可能会有用,但我不确定如何获得一个临时文件的
os.PathLike
对象

import tempfile
temp_file = tempfile.TemporaryFile('w')
json.dump('{"test": 1}', fp=temp_file)
file = open(temp_file.path(), 'r')
创造一个新的环境;它有一个
.name
属性,可以传递给函数:

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')
打开已打开的文件对象在Windows上确实存在问题(不允许);在这里,您必须首先关闭文件对象(确保在关闭时禁用删除),然后手动删除它:

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)
with
语句会在套件退出时关闭文件(因此当您到达
open()
调用时);它有一个
.name
属性,可以传递给函数:

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')
打开已打开的文件对象在Windows上确实存在问题(不允许);在这里,您必须首先关闭文件对象(确保在关闭时禁用删除),然后手动删除它:

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)
with
语句会在套件退出时关闭文件(因此当您到达
open()
调用时)