2017-04-26 74 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()