python - 尝试解析 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
解决方案
fname1 = print("'" + fname + "'")
分配None
给fname1
而不是打印的字符串。因此,正如错误所示,fname1
它属于NoneType
且无法打开。
编辑感谢@Jared Smith 为我解决这个问题
推荐阅读
- node.js - pnpm - node_modules 目录是否占用磁盘中的相同空间?
- r - R - Corrplot() 相关矩阵在网格中有问号。如何理解矩阵?
- ios - 为什么使用@IBAction func时UI没有及时更新?
- php - 搜索到的数据不显示
- javascript - 调用JS文件的最佳方式?
- javascript - 如何在单个按钮中添加更多功能
- markdown - 如何指定降价表的字体(或可选地使用 pandoc)?
- python - 是否可以在 scikit-learn 中实现 c4.5 算法?
- objective-c - Swift:对具有相同选择器的对象进行类型转换
- r - 使用函数内变量计算评估表达式