将json文件附加到文本文件

时间:2017-04-26 08:49:07

标签: python json

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

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

file.close()