Python 3.7 – insert filename at the start of every line in all .txt files in a folder

import os

def add_numbers(filename):
    with open(filename, 'r') as readfile:
        data = readfile.readlines()
    with open(filename, 'w') as writefile:
        for i, line in enumerate(data):
            writefile.write('%s. %s' % (filename, line))

for path, _, filenames in os.walk('.'):
    for filename in filenames:
        add_numbers(os.path.join(path, filename))

Leave a Comment