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

时间:2015-01-24 01:52:26

标签: 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'不是文件有关的错误。

2 个答案:

答案 0 :(得分:2)

json.load会获取类似文件的对象,并且您将其传递给包含该路径的str。试试这个:

path = os.path.abspath('theFile.json')
with open(path) as f:
    read_json(f)

请注意json.load返回字典,而不是字符串。此外,即使在finally:中引发异常,也会执行try:,因此即使发生错误和读取,您也始终记录"完成阅读"被中止了。

答案 1 :(得分:2)

=====修订=====

现在包含调用函数

的示例

尝试类似:

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