We should replace all all occurences of f = open(filepath, mode) by: with open(filepath, mode) as f: