Searching for strings in multiple text files and outputting matched lines to a CSV
16:36 29 Jan 2026

I have a folder full of hundreds of text files formatted like so:

holdrod =fl__2183_180325_0045  
  
  

measburn_tot =  189.260915   
 

I want to use Python to go through each file, search for 'holdrod' and 'measburn_tot' and print those lines to a CSV file so they appear like:

header 1 header 2 header 3 header 4
holdrod = fl__2183_180325_0045 measburn_tot = 189.260915

So far this is my code:

import re
import os
from pathlib import Path
import csv

file_directory = (r'/home/work_dir/FLrods')
files = os.listdir(file_directory)

for fname in files:
       if os.path.isfile(file_directory + os.sep + fname):
            f = open(file_directory + os.sep + fname, 'r')
            with open('output.csv', 'w') as outputCSV:
                writer = csv.writer(outputCSV)
                data = []
            for line in open(fname, 'r').read():
                search = re.compile('holdrod|measburn_tot')
                if search.match(line):
                    data.append(line.strip())
                    writer.writerow(data)

But this just returns an empty CSV file. Also, is my search variable correct? Shouldn't I be searching for both 'holdrod' and 'measburn_tot', since both lines are found in each file?

python string csv export-to-csv