解析文本文件并将这些值存储在Python字典中
我有一个文本文件,内容如下:
ID Value 1 Value 2
1 0.8 0.08
2 0.10 0.11
3 11 12
现在的问题是,我需要把这些值存储到一个Python字典里,并且写入一个文件中。
有没有人能帮我用Python做到这一点?
谢谢!
1 个回答
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)