从CSV文件+空行

时间:2015-07-17 14:48:10

标签: python csv

以下是我的代码!但是,当我运行它时,找不到名称? (它在CSV文件中如何)

import csv
name = "Andy"
score = "53"
x = 0
array = []

f = open('Class A.csv', 'r')
csv_file = csv.reader(f)
for row in csv_file:
    if row[0] == [name]:
        print("Found name")
        row[1].append(score)
        f.close()
        break
    else:
        print("Not found")
        f = open('Class A.csv', 'a')
        a = csv.writer(f)
        array.append(name)
        array.append(score)
        print(array)
        a.writerow(array)
        f.close()
        break

这是我的CSV文件:

Steve,3
Max,2
Dave,5
Andy,3

我对上述代码的第二个问题是,如果你写了两个不同的名字,它们之间会有一个空行。

1 个答案:

答案 0 :(得分:0)

打印的程序未找到,因为如果第一次比较没有匹配,那么您打印未找到,则需要迭代所有名称,如果没有匹配则插入新行。那是你的意图吗?

import csv
name = "Andy"
score = "53"
x = 0
array = []

f = open('Class A.csv', 'r')
csv_file = csv.reader(f)
is_found = False
for row in csv_file:
    if row[0] == name:
        print("Found name")
        is_found = True
        row.append(score)
        f.close()
        break
if not is_found:
        print("Not found")
        f = open('Class A.csv', 'a')
        a = csv.writer(f)
        array.append(name)
        array.append(score)
        print(array)
        a.writerow(array)
        f.close()