Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add new data in the existing column in csv with Python?

Original existing column.

I am trying to add new data to this column (red frame) in an existing csv file.

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

New data.

Here is the new data that I am trying to add to the existing file.

enter image description here

Output.

The output file must include the new data below the old one.

enter image description here

I had tried several ways to do it with python.

import pandas as pd
#original file
file_source = r"C:\Users\Material-Library.csv"
#New data
file_dest = r"C:\Users\empty.csv"

#read the original file
df = pd.read_csv(file_source)

#Find the column of new data that I want to copy into the original file
series_col = df.loc[:,'Desc']

#save the file
series_col.to_csv(file_dest, index=False)

However, the data in the original file was deleted and covered by the new one. It didn’t add to the original file.

>Solution :

Set your mode in to_csv to “a” for appending:

series_col.to_csv(file_dest, index=False, mode=“a”)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading