python - 将 json 文件传递​​给 Python 中的方法

标签 python json

我的计算机上有一个 json 文件,我需要将其传递给以下函数:

def read_json(file):
    try:
        logging.debug('Reading from input')
        return read_json_from_string(json.load(file))
    finally:
        logging.debug('Done reading')

如何将文件从我的计算机移动到 python 中的方法?我尝试了以下方法:

file = os.path.abspath('theFile.json')

然后尝试运行该方法

read_json(file)

但是我得到以下错误:

TypeError: expected file

我也试过:

file = open('theFile.json', 'r')

但我总是收到与"file"不是文件相关的错误。

最佳答案

=====已更新=====

现在包括一个调用函数的例子


尝试这样的事情:

import logging
import json

def read_json(file):
    try:
        print('Reading from input')
        with open(file, 'r') as f:
            return json.load(f)
    finally:
        print('Done reading')

return_dict = read_json("my_file.json")
print return_dict

关于python - 将 json 文件传递​​给 Python 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28121455/

相关文章:

json - Python3 : Grabbing data from Websocket and putting it into a DataFrame

python - 如何使用 matplotlib/seaborn 和 pandas 数据框创建具有共享 x 轴的倒置条形图

python - Selenium 中的 IF/THEN 语句

python - 将数组中的元素相乘 (Python)

json - 如何从获取响应正文捕获值 - 机器人框架

json - Jackson 反序列化意外 token (END_OBJECT),

python - 如何在python中删除firebase电子邮件身份验证用户?

Python;异常感知映射()

javascript - 获取 JSON 数组中的特定对象

javascript - 从字符串解析对象时,JSON 中出现意外的标记 &