'Reading a range of years (csv) into python

I'm looking to only read a range of years contained in the name of files in a directory. I have different files to read in, so this function is used on different 'filename' lists. The problem I'm having is when I have to list the year range where I want to read the files. Is there a concise way to do this?

Here's where I'm at so far:

import os
import pandas as pd

path_ = 'file/path'
train_insurance_files = [f for f in os.listdir(path_) if 'train_set_insurance' in f]

def load_train_files(filenames, years):
    
    train_filenames = [f for f in filenames if ['2012', '2013'] in f]
    
    for filename in train_filenames:
        yield pd.read_csv(filename)


Solution 1:[1]

You could do something like this:

def gen_list(lower_end, upper_end):
    res = []
    try:
        lower = int(lower_end)
        upper = int(upper_end)
        for x in range(upper - lower + 1):
            res.append(str(lower + x))
    except (TypeError, ValueError, Exception):
        pass
    return res


if __name__ == '__main__':
    if '2001' in gen_list('2000', '2005'):
        print('Is there')
    else:
        print('Is not there')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dan M