How to Append a New Row to a CSV File in Python?

Python Append Row to CSV

To append a row (=dictionary) to an existing CSV, open the file object in append mode using open('my_file.csv', 'a', newline=''). Then create a csv.DictWriter() to append a dict row using DictWriter.writerow(my_dict).

Given the following file 'my_file.csv':

You can append a row (dict) to the CSV file via this code snippet:

import csv

# Create the dictionary (=row)
row = {'A':'Y1', 'B':'Y2', 'C':'Y3'}

# Open the CSV file in "append" mode
with open('my_file.csv', 'a', newline='') as f:

    # Create a dictionary writer with the dict keys as column fieldnames
    writer = csv.DictWriter(f, fieldnames=row.keys())

    # Append single row to CSV
    writer.writerow(row)

After running the code in the same folder as your original 'my_file.csv', you’ll see the following result:

Append Multiple Rows to CSV

Given the following CSV file:

To add multiple rows (i.e., dicts) to an old existing CSV file, iterate over the rows and write each row by calling csv.DictWriter.writerow(row) on the initially created DictWriter object.

Here’s an example (major changes highlighted):

import csv

# Create the dictionary (=row)
rows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'},
        {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'},
        {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}]

# Open the CSV file in "append" mode
with open('my_file.csv', 'a', newline='') as f:

    # Create a dictionary writer with the dict keys as column fieldnames
    writer = csv.DictWriter(f, fieldnames=rows[0].keys())

    # Append multiple rows to CSV
    for row in rows:
        writer.writerow(row)

The resulting CSV file has all three rows added to the first row:

Python Add Row to CSV Pandas

To add a row to an existing CSV using Pandas, you can set the write mode argument to append 'a' in the pandas DataFrame to_csv() method like so: df.to_csv('my_csv.csv', mode='a', header=False).

df.to_csv('my_csv.csv', mode='a', header=False)

For a full example, check out this code snippet:

import pandas as pd

# Create the initial CSV data
rows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'},
        {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'},
        {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}]

# Create a DataFrame and write to CSV
df = pd.DataFrame(rows)
df.to_csv('my_file.csv', header=False, index=False)

# Create another row and append row (as df) to existing CSV
row = [{'A':'X1', 'B':'X2', 'C':'X3'}]
df = pd.DataFrame(row)
df.to_csv('my_file.csv', mode='a', header=False, index=False)

The output file looks like this (new row highlighted):

Alternatively, you can open the file in append mode using normal open() function with the append 'a' argument and pass it into the pandas DataFrame to_csv() method.

Here’s an example snippet for copy&paste:

with open('my_csv.csv', 'a') as f:
    df.to_csv(f, header=False)

🌍 Learn More: If you want to learn about 7 Best Ways to Convert Dict to CSV in Python, check out this Finxter tutorial.