我正在尝试与现有库进行交互,该库使用内置函数来使用表示路径的 str 或 bytes 对象或实现 os.PathLike protocol 的对象来open()读取文件。.json
我的函数生成一个字典,该字典转换为jsonusing json.dump(),但我不确定如何将其传递给需要文件路径的现有函数。
我想这样的东西可能会起作用,但我不确定如何获取os.PathLikeTemporaryFile 的对象。
import tempfile
temp_file = tempfile.TemporaryFile('w')
json.dump('{"test": 1}', fp=temp_file)
file = open(temp_file.path(), 'r')
Run Code Online (Sandbox Code Playgroud)
而是创建一个NamedTemporaryFile()对象;它有一个.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')
Run Code Online (Sandbox Code Playgroud)
在 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)
Run Code Online (Sandbox Code Playgroud)
该with语句导致文件在套件退出时关闭(因此当您到达调用时open())。
| 归档时间: |
|
| 查看次数: |
3331 次 |
| 最近记录: |