我正在从一个特定的目录中读取所有文本文件,并将它们写入一个json文件中。 我有以下错误:预期的str,字节或os.PathLike对象,而不是列表。有人知道如何解决吗?谢谢
import json
import glob
filepath = glob.glob( "path/*.txt")
line = []
data = []
with open(filepath) as fp:
line = fp.readline()
print(line)
cnt = 1
while line:
print("Object {}: {}".format(cnt, line.split(',')))
line = line.split(',')
#print(line)
data= []
try:
data.append({
'FileName': filepath,
'bbox_left': line[0],
'bbox_top': line[1],
'bbox_width': line[2],
'bbox_height': line[3],
'Score': line[4],
'Object_category': line[5],
'Truncation': line[6],
'Occlusion': line[7]
})
with open('data.json', 'a') as outfile:
json.dump(data, outfile)
except Exception as e:
print(e)
line = fp.readline()
cnt += 1
答案 0 :(得分:1)
这里的文件路径是“文件路径”的列表,而不仅仅是一个“文件路径”,因此open()
抱怨它接受的是字符串而不是列表
您的代码应如下所示,我已对其进行了一些修改,请花一些时间查看发生的事情
import json
import glob
filepaths = glob.glob("path/*.txt")
line = []
data = []
for filepath in filepaths:
with open(filepath) as fp:
for cnt, line in enumerate(fp.readlines()):
line = line.split(',')
print("Object {}: {}".format(cnt, line))
try:
data.append({
'FileName': filepath,
'bbox_left': line[0],
'bbox_top': line[1],
'bbox_width': line[2],
'bbox_height': line[3],
'Score': line[4],
'Object_category': line[5],
'Truncation': line[6],
'Occlusion': line[7]
})
except Exception as e:
print(e)
with open('data.json', 'a') as outfile:
json.dump(data, outfile)