To append to an existing CSV file with pandas, you can use the to_csv() function and pass “mode=’a'” to specify you want to append to the CSV file.
df.to_csv('example.csv', mode='a', index=False, header=False)
When outputting data to different types of files, the ability to append to a file easily is valuable.
One such case is if you want to append to an existing CSV file in Python with pandas.
To write a pandas DataFrame to a CSV, you can use the to_csv() function. If you want to add data to a CSV file, you can use the same function and pass some additional arguments.
For adding rows to an existing CSV file, you should pass “mode=’a'” to specify you want to append to the CSV. You should also pass “header=False” because the CSV will most likely already have a header.
One final argument you can pass a value to is the ‘index’ argument. Depending on whether or not the existing CSV already has an index or not, you will want to set this to True or False.
If you don’t use the “index” argument, it’s possible that your output will not be suitable for downstream processes which depend on the CSV file.
Below is an example showing you how you can use to_csv() to append to an existing CSV file with pandas in Python.
df.to_csv('example.csv', mode='a', index=False, header=False)
Hopefully this article has been useful for you to learn how to add to an existing CSV file with pandas.