Skip to content
Advertisement

Python 3: CSV Module

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

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement