【发布时间】: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