[Solved] Merging txt files whose last letters repeat in python [closed]


For simplicity, this script assumes that it is being run from the same directory as the files you described in the question (this can be easily modified). It finds all the files that end with four-digits plus .txt, groups them together by the starting characters (before '_') and writes the contents of each into a single file with those same starting characters plus _allyears.txt.

from glob import glob
from itertools import groupby

filenames = sorted(glob('*_[0-9][0-9][0-9][0-9].txt'))

for k, g in groupby(filenames, key=lambda f: f.rsplit('_', 1)[0]):
    with open('{}_allyears.txt'.format(k), 'w') as outfile:
        for filename in g:
            with open(filename, 'r') as infile:
                outfile.write(infile.read())

4

solved Merging txt files whose last letters repeat in python [closed]