简体   繁体   中英

How to replace one value with another in a csv file?

I have a CSV file with information and want to replace the information in a specific location with a new value.

For example if my CSV file looks like this:

example1,example2,0

example3,example4,0

exampple5,example6,0

Note that each row is labelled for example:

test = row[0]

test1 = row[1]

test2 = row[2]

If I want to replace

test[0]

with a new value how would I go about doing it?

Simplest way without installing any additional package would be to use built-in csv to read the whole file in a matrix and replace the desired element.

Here is code that would do just that:

import csv

with open('test.csv', 'r') as in_file, open('test_out.csv', 'wb') as out_file:
    data = [row for row in csv.reader(in_file)]
    data[0][0] = 'new value'
    writer = csv.writer(out_file)
    writer.writerows(data)

There are a handful of ways to do this, but personally I'm a big fan of pandas. With pandas, you can read a csv file with df = pd.read_csv('path_to_file.csv') . Make changes however you want, if you wanted row 1 column 1, you'd use df.loc[0,0] = new_val . Then when you are done save to the same file df.to_csv('path_to_file.csv') .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM