Home > Back-end >  How to add new data in the existing column in csv with Python?
How to add new data in the existing column in csv with Python?

Time:05-29

Original existing column.

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

enter image description here

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.

CodePudding user response:

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

series_col.to_csv(file_dest, index=False, mode=“a”)
  • Related