为了合并几个文件,你可以使用这样的函数,利用 Python 的defaultdict
:
def read_from_file(filename, dictionary):
with open(filename) as f:
lines = f.read().splitlines()
head, body = lines[0].split(), lines[1:]
for line in body:
for i, item in enumerate(line.split()):
if i == 0:
d = dictionary[item]
else:
d[head[i]] = item
from collections import defaultdict
from pprint import pprint
d = defaultdict(defaultdict)
read_from_file("file1", d)
read_from_file("file2", d)
read_from_file("file3", d)
pprint(dict(d))
输出:
{'001': defaultdict(None, {'Var1': '5', 'Var2': '10'}),
'002': defaultdict(None, {'Var1': '12', 'Var2': '6'}),
'003': defaultdict(None, {'Var5': '9', 'Var1': '5', 'Var3': '10'}),
'004': defaultdict(None, {'Var5': '1', 'Var1': '12', 'Var3': '6'}),
'005': defaultdict(None, {'Var4': '10', 'Var3': '5'}),
'006': defaultdict(None, {'Var4': '6', 'Var3': '12'})}
现在剩下要做的就是把这个字典漂亮地打印成一个表格。