Exercise: Write tests for script combining files
- This is a solution for one of the exercises in which we had to combine two files adding the numbers of the vegetables together.
- Many things could be improved, but before doing that, write a test (or two) to check this code. Without changing it.
examples/dictionary/combine_files.py
c = {} with open('examples/files/a.txt') as fh: for line in fh: k, v = line.rstrip("\n").split("=") if k in c: c[k] += int(v) else: c[k] = int(v) with open('examples/files/b.txt') as fh: for line in fh: k, v = line.rstrip("\n").split("=") if k in c: c[k] += int(v) else: c[k] = int(v) with open('out.txt', 'w') as fh: for k in sorted(c.keys()): fh.write("{}={}\n".format(k, c[k]))
Data Files:
examples/files/a.txt
Tomato=78 Avocado=23 Pumpkin=100
examples/files/b.txt
Cucumber=17 Avocado=10 Cucumber=10