首页 > 解决方案 > 尝试解析 JSON 文件时不理解此 TypeError

问题描述

TypeError: expected str, bytes or os.PathLike object, not NoneType当我尝试读取和解析 json 文件时出现错误。我在网上检查了这个错误,并在stackoverflow上偶然发现了这个链接——

TypeError:预期的 str、字节或 os.PathLike 对象,而不是 _io.BufferedReader

但上面看起来像同样的问题,但解决方案不适用于我的代码。

下面的代码:

# function to parse the json file and extract useful information
def json_parser(file):
    print(file)
    with open(file, 'r') as fp:
        json_decode = json.loads(fp.read())
        pprint(json_decode)
        return json_decode

# script to read through the directories and parse json files

rootDir = 'projects/dataset'
for dirName, subdirList, fileList in os.walk(rootDir):
    print("Found directory: %s" % dirName)
    for fname in fileList:
        print('\t%s' % fname)
        fname1 = print("'" + fname + "'")
        # calling the json parser function defined above
        result = json_parser(fname1)
        print(result)

追溯:

Error: File "test_json_parsing.py", line 15, in json_parser
    with open(file, 'r') as fp:
TypeError: expected str, bytes or os.PathLike object, not NoneType

标签: pythontypeerror

解决方案


fname1 = print("'" + fname + "'")分配Nonefname1而不是打印的字符串。因此,正如错误所示,fname1它属于NoneType且无法打开。

编辑感谢@Jared Smith 为我解决这个问题


推荐阅读