Add a Column to an existing CSV file with Python

csv, import, python, python-2.7

Solution

If using pandas is an option:

import pandas as pd
df = pd.read_csv('filename.csv')
new_column = pd.DataFrame({'new_header': ['new_value_1', 'new_value_2', 'new_value_3']})
df = df.merge(new_column, left_index = True, right_index = True)
df.to_csv('filename.csv', index = False)

Problem

I'm trying to add a new column header and values to an existing csv file with python. Every thing I've looked up appends the header to the last row of the last column. This is what I want my results to be essentially. `Header Header2 Header3 NewHeader Value Value2 Value3 NewValue` What I'm currently getting is this: ``` Header Header2 Header3 Value Value2 Value3**NewHeader NewValue` ``` This is my code: ``` import csv with open('filename.csv', 'a') as csvfile: fieldnames = ['pageviewid'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerow({'pageviewid': 'Baked'}) writer.writerow({'pageviewid': 'Lovely'}) writer.writerow({'pageviewid': 'Wonderful'}) ```

Original source