2017-07-15 221 views
1

我想將文件轉換爲json。 文件的格式爲:python - 從txt文件到字典和json

Temp=24.0* Humidity=41.0% Date=02/01/17-20:37 
Temp=24.0* Humidity=42.0% Date=02/01/17-20:38 
Temp=24.0* Humidity=42.0% Date=02/01/17-20:39 

我用下面的代碼:

list = {} 
with open("record.txt") as f: 
    for line in f: 
    if not ("Failed" in line): 
     lists = line.split(" ") 
     for l in lists: 
     ll = dict([l.split("=")]) 
     // print(json.dumps(ll)) 
     list.update(ll) 

當我打印字典創建我得到。

>>> print (list) 
{'Temp': '29.0*', 'Humidity': '31.0%', 'Date': '15/07/17-10:56\n', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Temp': '21.0*'} 

我不明白爲什麼。有誰知道我爲什麼沒有收到整本字典?

在轉換爲json之前,我還將用新行/n分隔到子字典。這可能嗎?

+1

您正在重寫每次迭代中的值。 – badiya

回答

1

輸入文件包含相同的組唯一密鑰如此三次Python中的相應表示,其然後可以被序列化到JSON,是字典的陣列。

試試這個改變了代碼: list = [] with open("record.txt") as f: for line in f: if not ("Failed" in line): lists = line.rstrip().split(" ") ll = {} for l in lists: k,v = l.split("=") ll[k] = v list.append(ll)

如果你再這樣做: print list

你應該得到: print list [{'Date': '02/01/17-20:37', 'Temp': '24.0*', 'Humidity': '41.0%'}, {'Date': '02/01/17-20:38', 'Temp': '24.0*', 'Humidity': '42.0%'}, {'Date': '02/01/17-20:39', 'Temp': '24.0*', 'Humidity': '42.0%'}]

然後你可以轉儲到JSON有: import json json.dumps(list) '[{"Date": "02/01/17-20:37", "Temp": "24.0*", "Humidity": "41.0%"}, {"Date": "02/01/17-20:38", "Temp": "24.0*", "Humidity": "42.0%"}, {"Date": "02/01/17-20:39", "Temp": "24.0*", "Humidity": "42.0%"}]'

+0

正是我想要做的,謝謝! –

0

你可以創建一個這樣的字典列表,然後可以做任何你想做的修改。

list = {} 
complete_list=[] 
with open("record.txt") as f: 
    for line in f: 
    if not ("Failed" in line): 
     lists = line.split(" ") 
     lists[-1] = lists[-1].strip()  #it should remove the \n at the end. 
     for l in lists: 
     ll = dict([l.split("=")]) 
     // print(json.dumps(ll)) 
     list.update(ll) 
     complete_list.append(list)