0

Python how can I append data to a csv file without over-writing other colums?

I am trying to write a code that receives list data and append it to different columns without overwriting existing columns.

20th Jan 2021, 11:40 PM
Karzan
4 Réponses
+ 2
Use the append file mode, "a", in the open statement.
21st Jan 2021, 1:21 AM
Brian
Brian - avatar
+ 2
Karzan You can read the csv first using pandas then concatenate your data, then save to a new file. import pandas as pd df_1 = read_csv(" file ") dict = { column_name : contents, ... } df_2 = pd.DataFrame(dict) new_df = df.concat( [df_1, df_2], axis = 0) # concatenate vertically new_df = df.concat( [df_1, df_2], axis = 1) # concatenate horizontally new_df.to_csv("new file")
23rd Jan 2021, 1:45 AM
noteve
noteve - avatar
+ 1
This is what I mean: open("myfile.csv", "a") The "a" lets you add new rows at the end of the file without overwriting existing rows. Also if the file does net yet exist, then it creates the file for you and lets you write to it. So I had in mind that you wanted to add more rows. But did you mean to extend existing rows by adding more columns to the rows? If so, then you will have to rewrite the whole file from beginning to end with the original data plus the added columns. I recommend reading the original file as read only ("r"), updating the row data in memory, and writing the result to a different output file.
21st Jan 2021, 8:35 AM
Brian
Brian - avatar
0
Brian can you please share an example?
21st Jan 2021, 4:19 AM
Karzan