I have multiple csv files with date as filename (20080101.csv to 20111031.csv) in a folder. The csv files have common headers. The csv file looks like this:
The following should work:
import csv
with open('output.csv', 'w') as outfile:
outfile.write('X ; Y ; Z ; filename\n')
fmt = '1 ; 2 ; %s ; %s\n'
files = ['20080101.csv', '20080102.csv', '20080103.csv', '20080104.csv']
for file in files:
with open(file) as f:
reader = csv.reader(f, delimiter=';')
for row in reader:
if len(row) > 2 and row[0].strip() == '1' and row[1].strip() == '2':
outfile.write(fmt % (row[2].strip(), file[:-4]))
break
else:
outfile.write(fmt % ('NA', file[:-4]))