Function using DictReader to add new column with default value

I’m trying to create a function that takes in a csv file and creates a new column with a default value, both of which can be supplied.

Below is my attempt. But it fails to pass col_name as an argument. How do I overcome this?

def main(input_file_path, col_name, col_value, output_file_path):
    with open(input_file_path, 'r') as inf, open(output_file_path, 'w') as outf:
        csvreader = csv.DictReader(inf)
        fieldnames = csvreader.fieldnames + [col_name] # add column name to beginning
        print(fieldnames)
        csvwriter = csv.DictWriter(outf, fieldnames)
        csvwriter.writeheader()
        for node, row in enumerate(csvreader, 1):
            csvwriter.writerow(dict(row, col_name=col_value))

Output

ValueError: dict contains fields not in fieldnames: 'col_name'

Answer

When you write col_name = col_value, col_name is used literally, it’s not evaluated as a variable.

You should add the column to row.

        for node, row in enumerate(csvreader, 1):
            row[col_name] = col_value
            csvwriter.writerow(row)

BTW, why are you using enumerate()? You never use node.