0

I am working with a simple csv file and want to know how to update the values contained in a specific cell on each row using data my script has generated.

column1, column2, colum3, column4,
bob, 20, blue, hammer
jane, 30, red, pencil
chris, 40, green, ruler

Then:

new_colour = [pink, yellow, black]

Is there a way to take the list <new_colour> and write each list item into the values under colum3 within the csv file? To have it end up like below:

column1, column2, colum3, column4,
bob, 20, pink, hammer
jane, 30, yellow, pencil
chris, 40, black, ruler

Thank you

5
  • 1
    What exactly is your question? Commented Nov 22, 2022 at 23:53
  • 1
    please add a clear, answerable question to your post Commented Nov 22, 2022 at 23:54
  • 'test_domain_application_data.csv' has the data you want to update? You want to read the existing CSV, update the data, then write. What are the rules for what you want to overwrite? make this a small working example and we'll have a better chance at answering. Commented Nov 22, 2022 at 23:58
  • Sorry, I have updated my Q to attempt to be more clear. Commented Nov 23, 2022 at 9:42
  • You'll need to load the CSV into your Python script, and write out a new, modified one. If it is very large, do it "on-the-fly" i.e. reading, modifying and writing as you go. If it is small, and it's simpler, read the whole CSV, modify and then write in one go. You can delete or rename the existing CSV as XXX.csv.bkup before writing the new file. If there are other processes simultaneously accessing the CSV while you change it, save the new file as XXX.csv.inprogress till it is completely written then rename it when complete so everyone gets a consistent view. Commented Nov 23, 2022 at 10:05

1 Answer 1

2

One (probably unoptimized) solution could be using the pandas module, as long as your CSV file is not too big:

PATH_TO_CSV = <your_path>
new_colour = ['pink', 'yellow', 'black']

df = pd.read_csv(PATH_TO_CSV)
df['colum3'] = pd.Series(new_colour)
df.to_csv(PATH_TO_CSV)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.