附加JSON文件到文本文件

2024-10-06 12:38:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,其中每个元素都是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'

如何解决这个问题?你知道吗


Tags: 文件inpyjsonliblineloadusers
1条回答
网友
1楼 · 发布于 2024-10-06 12:38:28

json的串联不是json,句号。此文件是有效的Json:

[ 1, 2 ,
  { "a": "b" },
  3 ]

给这个Python对象:[1, 2, {'a': 'b'}, 3]

但这不再是有效的json文件:

[ 1, 2 ,
  { "a": "b" },
  3 ]
[ 1, 2 ,
  { "a": "b" },
  3 ]

因为它包含2个没有关系的对象。你知道吗

您应该将所有内容都包含在外部列表中以使其有效:

[
[ 1, 2 ,
  { "a": "b" },
  3 ]
,
[ 1, 2 ,
  { "a": "b" },
  3 ]
]

所以生成代码应该是:

file=open("abc.txt","a")
file.write("[\n")            # start of a list
first = True
for i in range(len(list))
    if first: 
        first = False
    else: 
        file.write(",\n")    # add a separating comma before every element but the first one
    with open(list[i]) as f:
        u=json.load(f)
        s=json.dumps(u)
        file.write(s)
file.write("]\n")            # terminate the list

你知道吗文件.close()

相关问题 更多 >