5

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'.

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

4 Comments

I have tried doing this originally but I get this error: 'if line[3] == 'r': IndexError: list index out of range'
note that the 'r' in 'if line[3] == 'r' '. I changed my code to reflect 'r' instead of 'a'
You must have empty lines. I have added a length check on the row.
actually, I just tried the top code you put in there. thats working now, thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.