Home > OS >  How do I update every row of one column of a CSV with Python?
How do I update every row of one column of a CSV with Python?

Time:08-26

I'm trying to update every row of 1 particular column in a CSV. My actual use-case is a bit more complex but it's just the CSV syntax I'm having trouble with, so for the example, I'll use this:

Name Number
Bob 1
Alice 2
Bobathy 3

If I have a CSV with the above data, how would I get it to add 1 to each number & update the CSV or spit it out into a new file?

How can I take syntax like this & apply it to the CSV?

test = [1,2,3]
for n in test:
     n = n 1
     print(n)

I've been looking through a bunch of tutorials & haven't been able to quite figure it out.

Thanks!


Edit: I can read the data & get what I'm looking for printed out, my issue now is just with getting that back into the CSV

import csv
with open('file.csv', newline='') as csvfile:

    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['name'], (int (row['number'])  1) )
└─$ python3 test_csv_script.py
bob 2
alice 3
bobathy 4

CodePudding user response:

You can open another file, out.csv, which you write the new data into.

For example:

import csv
with open('file.csv', newline='') as csvfile, open('out.csv', 'w') as file_write:
    reader = csv.DictReader(csvfile)
    for row in reader:
        file_write.write(row['name'], (int (row['number'])  1) )

CodePudding user response:

Thank you Mark Tolonen for the comment - that example was very helpful & led me to my solution:

import csv
with open('file.csv', newline='') as csv_input, open('out.csv', 'w') as csv_output:
    reader = csv.reader(csv_input)
    writer = csv.writer(csv_output)

    # Header doesn't need extra processing
    header = next(reader)
    writer.writerow(header)

    for name, number in reader:
        writer.writerow([name, (int(number) 1)])

 


Also sharing for anybody who finds this in the future, if you're looking to move the modified data to a new column/header, use this:

import csv
with open('file.csv', newline='') as csv_input, open('out.csv', 'w') as csv_output:
    reader = csv.reader(csv_input)
    writer = csv.writer(csv_output)

    header = next(reader)
    header.append("new column")
    writer.writerow(header)

    for name, number in reader:
        writer.writerow([name, number, (int(number) 1)])
  • Related