Python编辑csv文件的特定行和列

时间:2016-10-20 08:13:00

标签: python-3.x csv

我在这里有一些python代码,目的是将用户输入定位到CSV的特定行,然后在某个字母匹配时覆盖它。

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)

这段代码几乎按照我想要的方式工作,但是除了第一行之外,它无法编辑任何其他行。这段代码输出的一个例子是:

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

问题我然后将其定位到另一行,例如行'blue,42.5,a'。我的代码无法定位,然后将值'a'更改为'b'。

1 个答案:

答案 0 :(得分:2)

您正在title上进行迭代并更改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) 。这样做:

title = next(reader)

并删除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) ,因为您没有标题。

没有标题行的输入csv的完整固定代码:

#include<stdio.h>
int main()
{
    int a, b, c, d, max;

     printf("Enter three numbers: ");
     scanf("%d%d%d%d", &a, &b, &c);
     max=a;
     if (max<b) {max=b;}
     if (max<c) {max=c;}
     printf("the greatest number is %d\n", max);


     return 0;
 }