0

I am trying to insert (update) values in a csv file whenever my code runs.

Here is my csv file content:

col1 | col2 | col3
value1,value2,value3

When I run my code, I want to only update value3 that is in col3. For example it would look like this after I run my script:

 col1 | col2 | col3
 value1,value2,newly_inserted_value3

Here is my code:

import csv
from csv import writer

file_name = 'my_file.csv'
with open(file_name, 'wb') as obj:
    # Create a writer object from csv module
    csv_writer = writer(obj)
    # Add contents of list as last row in the csv file
    csv_writer.writerow('new_value3')

However, it doesn't only insert the "new_value3" in col3. I am new to python so any ideas or suggestion would help.

James
  • 27
  • 6
  • Not quite, it doesn't save the values to the actual csv file – James Oct 08 '20 at 16:44
  • I think you're failing to break the problem into distinct steps, each of which are entirely disjoint problems: (1) read CSV (2) modify value in a cell (3) write the CSV to file. I assume you can do step (3) if you have completed (1) and (2). If not, see [this](https://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files-with-python). – ggorlen Oct 08 '20 at 16:50

1 Answers1

0

The tagged library pandas is great for handling csvs. Use the following code structure:

import pandas as pd
df = pd.read_csv('/path/to/a.csv')
df = apply_your_functions_on_dataframe(df)
df.to_csv('/path/to/your/output.csv')

The object output by pd.read_csv is called a pd.DataFrame (tutorial here:https://pandas.pydata.org/pandas-docs/stable/user_guide/10min.html). Pandas will handle all the writing and reading of csvs for you, so all left for you is the actual operation you would like to perform on the dataframe, which is basically a table.

In your example, try to use: df.loc[0, 'col3'] = new_value3, it should work.

yonatansc97
  • 584
  • 6
  • 16