我的文本文件如下
ID Value 1 Value 2
1 0.8 0.08
2 0.10 0.11
3 11 12
现在问题是我必须将这些值存储在python字典中并写入文件..
任何人都可以使用python
帮助我如何做到这一点由于 Ñ
答案 0 :(得分:4)
将文件读入dict非常简单:
# 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']}
您想用什么格式将dict写回来?如果你想把它写回大致相同的格式(我假设它最初是以空格分隔的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)