2011-07-09 20 views
-1

我的文本文件如下解析文本文件,然後將這些值存儲在Python字典

ID Value 1 Value 2 

1  0.8  0.08 
2  0.10  0.11 
3  11   12 

現在的問題是,我必須將這些值存儲在Python字典和寫入文件..

任何人可以幫助我如何做到這一點使用python

感謝 ň

+2

+1什麼喬說,告訴我們您將如何去做,我們將提供建議和更正 – slezica

+4

如果你的數據已經存在於一個文件中,並且你想將這個文件讀入一個字典然後返回到一個文件,那麼看起來完成的唯一的事情就是刪除帶有重複鍵的行。這是你想要完成的嗎?關鍵是什麼?標識?如果是這樣,這些ID是否已經是唯一的? –

回答

4

文件讀入一個字典是相當容易:

# use with statement to open the file 
with open(file_name) as f: 
    # skip first two lines (containing header) and split on whitespace 
    # this creates a nested list like: [[val1, i1, i2], [val2, i1, i2]] 
    lines = [x.split() for x in f.readlines()[2:] 
    # use the list to create the dict, using first item as key, last as values 
    d = dict((x[0], x[1:]) for x in lines) 

這給你喜歡的字典:

{'1': ['0.8', '0.08'], '2': ['0.10', '0.11'], '3': ['11', '12']} 

什麼格式你想用寫字典背出來?如果你想將它寫回到大致相同的格式(我假設它原是空格分隔CSV):

import csv 

writer = csv.writer(open(out_filename, 'w'), delimiter=' ') 
# write header 
writer.writerow(['ID', 'Value 1', 'Value 2']) 
# write each row 
for k,v in d.items(): 
    writer.writerow([k] + v) 
相關問題