我有一个列表,其中每个元素都是json文件的路径。我正在使用以下代码写入文本文件:
list=['C:/Users/JAYANTH/Desktop/datasets/580317556516483072/source-
tweet/580317556516483072.json',
'C:/Users/JAYANTH/Desktop/datasets/580317998147325952/source-
tweet/580317998147325952.json',
..........]
file=open("abc.txt","a")
for i in range(len(list))
with open(list[i]) as f:
u=json.load(f)
s=json.dumps(u)
file.write(s)
file.close()
这段代码将json文件中的数据附加到txt文件中。尝试使用以下代码从同一文件读取数据时:
with open('abc.txt','r') as f:
for each in f:
print(json.load(file))
我得到以下错误:
Traceback (most recent call last):
File "C:\Users\JAYANTH\Desktop\proj\apr25.py", line 15, in <module>
print(json.load(file))
File "C:\Users\JAYANTH\Desktop\proj\lib\json\__init__.py", line 268, in
load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook,
**kw)
File "C:\Users\JAYANTH\Desktop\proj\lib\json\__init__.py", line 319, in
loads
return _default_decoder.decode(s)
File "C:\Users\JAYANTH\Desktop\proj\lib\json\decoder.py", line 339, in
decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\JAYANTH\Desktop\proj\lib\json\decoder.py", line 357, in
raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
我也试过使用json.loads文件,但出现错误:
Traceback (most recent call last):
File "C:\Users\JAYANTH\Desktop\proj\apr25.py", line 15, in <module>
print(json.loads(file))
File "C:\Users\JAYANTH\Desktop\proj\lib\json\__init__.py", line 312, in
loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'TextIOWrapper'
如何解决这个问题?你知道吗
json的串联不是json,句号。此文件是有效的Json:
给这个Python对象:
[1, 2, {'a': 'b'}, 3]
但这不再是有效的json文件:
因为它包含2个没有关系的对象。你知道吗
您应该将所有内容都包含在外部列表中以使其有效:
所以生成代码应该是:
你知道吗文件.close()
相关问题 更多 >
编程相关推荐