interesting! Let's take a look.
The design is pretty simple. Read the file into a dictionary and perform manipulation on the dict, then write out the files.
with open('file1.txt') as in_:
mapping = {}
for line in in_:
key,value = line.strip().split(',')
mapping[key] = int(value)
mapping
is now {"a":1, "b":3, "c":5, "d":-4}
Let's read in our files.
values = {}
with open('file2.txt') as in_:
for _ in range(3):
# This is ugly, but it's a quick hack. I'd improve it later.
cur_dict = next(in_).strip()
values[cur_dict] = {}
for __ in range(4):
key, value = next(in_).strip().split(',')
values[cur_dict][key] = int(value)
Sheesh that's probably the ugliest code I've ever written, but values
is now {"sample1": {"a":12, "b":10, "c":4, "d":6}, "sample2": ...}
Now for the manipulation. This is actually easy. Let's tack file write onto it, since this step is rather elementary
for dataset in values:
for key, value in mapping.items():
values[dataset][key] += value
with open(dataset + ".txt") as out:
out.write(dataset)
for key,value in values[dataset]:
out.write("{},{}\n".format(key,value))