С учетом входного файла headers.csv
:
row1,row2,row3,row4,row5,bad,good,eight,nine,queen,three,eighteen,nineteen,king,jack,ace,we,them,you,two
Ваш код генерирует следующий код:
import csv
dictionary_list = [{"eight": "yes", "queen": "yes", "we": "yes", "eighteen": "yes"},
{"nine": "yes", "king": "yes","we": "yes", "nineteen": "yes"}]
# Read the input header line as a list
with open('headers.csv',newline='') as f:
reader = csv.reader(f)
headers = next(reader)
# Generate the fixed values for the first 5 rows.
rowvals = dict(zip(headers[:5],['x'] * 5))
with open('file.csv', 'w', newline='') as f:
# When writing a row, restval is the default value when it isn't in the dict row.
# extrasaction='ignore' prevents complaining if all columns are not present in dict row.
writer = csv.DictWriter(f,headers,restval='no',extrasaction='ignore')
writer.writeheader()
for dictionary in dictionary_list:
D = dictionary.copy() # needed if the original shouldn't be modified.
D.update(rowvals)
writer.writerow(D)
Вывод:
row1,row2,row3,row4,row5,bad,good,eight,nine,queen,three,eighteen,nineteen,king,jack,ace,we,them,you,two
x,x,x,x,x,no,no,yes,no,yes,no,yes,no,no,no,no,yes,no,no,no
x,x,x,x,x,no,no,no,yes,no,no,no,yes,yes,no,no,yes,no,no,no