【问题标题】:Python edit specific row and column of csv filePython编辑csv文件的特定行和列
【发布时间】:2016-10-20 08:12:59
【问题描述】:

我在这里有一些 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”。

【问题讨论】:

    标签: python-3.x csv


    【解决方案1】:

    您正在迭代 line 并且您更改了 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),因为您没有标题。

    没有标题行的输入 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=',')
    
        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)
    

    【讨论】:

    • 我最初尝试过这样做,但出现此错误:'if line[3] == 'r': IndexError: list index out of range'
    • 请注意,'if line[3] == 'r' 中的 'r'。我更改了代码以反映“r”而不是“a”
    • 你必须有空行。我在行上添加了长度检查。
    • 实际上,我只是尝试了您输入的最高代码。现在可以了,非常感谢您
    猜你喜欢
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 2011-06-10
    • 1970-01-01
    相关资源
    最近更新 更多