100 days of code: Day 19 - module

Last modified on 2020-06-27

Source: 100-days-of-code.

A module of functions allows me to create (hopefully!) more simple and robust Python programs by separating the how from the what. For my weight tracking I create two files: datetag.py as a module of functions that I import into dates_weights.py and use to find my desired patterns.

Module datetag.py is written (how) to find any pattern given a filename, a Python regular expression, and (optional) a filename to save the output …

import re
import json

def make_pattern_object(pattern):
    """Make a regex pattern object."""
    regex = fr"{pattern}"
    pattern_object = re.compile(regex, re.MULTILINE)
    return pattern_object


def save_data(data, filename):
    """Save data to file in the JSON format."""
    with open(filename, 'w+') as f:
        json.dump(data, f)


def make_list(source_file, pattern, save_file=''):
    """Retrieve measurements and dates they were recorded
    from <source_file> and return as a list.
    """
    try:
        with open(source_file) as f:
            contents = f.read()
            p = make_pattern_object(pattern)
            match_list = re.findall(p, contents)
            if save_file:
                save = f'{save_file}.json'
                save_data(match_list, save)
        return match_list
    except FileNotFoundError:
        print(f"\nError: File '{filename}' not found.")

Happy hacking!