2017-04-26 70 views
0

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

我该如何解决这个问题?

+0

“ abc.txt“,为什么你有一个for循环。只需打印(json.load(f)) – Ashish

+0

为什么你想这样做?您可以创建一个外部列表,将每个单独的json对象附加到此列表列表中,该列表本身将成为单个有效的json对象。然后把它写到一个文件中。 – roganjosh

回答

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()