We help IT Professionals succeed at work.

Python Append to existing csv file

Wm Allen Smith
on
How to append to an existing csv file? I have a csv file that is the result of looping through a folder and extracting data from named excel sheets within the folder. The the dataframe is saved as a csv file. Everytime the process runs it overwrites the content in the csv--I want to append to the file with new rows of data from each run, , not overwrite it. Please advise.
Comment
Watch Question

CERTIFIED EXPERT
Commented:
The key point is using 'a' for appending when you open the file.

import csv  
fields=['x','y','z']
with open(r'name', 'a') as f:
    writer = csv.writer(f)
    writer.writerow(fields)
Analyst Assistant
CERTIFIED EXPERT
Commented:
At the beginning of the code instead of starting with an empty data frame read in the CSV, if it exists, into a dataframe and append to that.
Thanks, guys, I will try this.