Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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.
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:

Tomato=78
Avocado=23
Pumpkin=100
Cucumber=17
Avocado=10
Cucumber=10