Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python edit specific row and column of csv file

Tags:

python-3.x

csv

I have some python code here with the aim of taking user input to target a specific row of a CSV and then to overwrite it if a certain letter matches.

import csv

line_count = 0
marked_item = int(input("Enter the item number:"))
with open("items.csv", 'r') as f:
    reader = csv.reader(f, delimiter=',')
    title = next(reader)
    print(title)
    print(title[3])
    lines = []
    for line in reader:
        if title[3] == 'a':
            line_count += 1
            if marked_item == line_count:
                title[3] = 'b'
        lines.append(line)
with open("items.csv", 'w', newline='') as f:
    writer = csv.writer(f, delimiter=',')
    writer.writerow(title)
    writer.writerows(lines)

This code works almost the way I want it to but it is unable to edit any other row but the first. an example of the output this code is:

red,12.95,2,b #note, this change from 'a' to 'b'
blue,42.5,3,a #How can I target this row and change it?
green,40.0,1,a

the problem I then have it targeting another row like row 'blue,42.5,a'. My code is unable to target and then change the value 'a' to 'b'.

like image 343
core_light Avatar asked Oct 20 '16 08:10

core_light


People also ask

How do I rewrite a specific row in a CSV file in Python?

The join() method takes all lines of a CSV file in an iterable and joins them into one string. Then, we can use replace() method on the entire string and can perform single/multiple replacements. In the entire string, the given text is searched and replaced with the specified text.


1 Answers

you're iterating on line and you change title. Do this:

for line in reader:
    if len(line)>3 and line[3] == 'a':
        line_count += 1
        if marked_item == line_count:
            line[3] = 'b'
    lines.append(line)

and drop the title = next(reader) since you don't have a title.

full fixed code for input csvs that don't have a title line:

import csv

line_count = 0
marked_item = int(input("Enter the item number:"))
with open("items.csv", 'r') as f:
    reader = csv.reader(f, delimiter=',')

    lines = []
    for line in reader:
        if len(line)>3 and line[3] == 'a':
            line_count += 1
            if marked_item == line_count:
                line[3] = 'b'
        lines.append(line)
with open("items.csv", 'w', newline='') as f:
    writer = csv.writer(f, delimiter=',')
    writer.writerow(title)
    writer.writerows(lines)
like image 191
Jean-François Fabre Avatar answered Nov 03 '22 05:11

Jean-François Fabre