将列写入CSV文件

时间:2018-07-09 11:30:48

标签: python csv

我想为csv文件中的特定行更新名为Score的列。当按下按钮时,我希望代码搜索csv文件,直到找到具有指定名称的行(该行存储在变量name中,并在以前的功能{{ 1}}),并更新NameGenerator()列中的相关单元格以增加1。

请注意,我正在为此使用另存为.csv的Excel文件。

任何想法如何做到这一点?下面的代码不起作用。任何帮助将不胜感激。

Score

![The CSV file looks as follows ] 1 因此,例如,如果选择了名称tom(在代码的其他位置,但是存储在变量def Correct(): writer = csv.writer(namelist_file) score=0 for row in writer: if row[0] == name: score=score+1 writer.writerow([col[1]] = score) 中),则他的分数3应该增加1,变成4。

这是从csv文件中提取随机名称的函数的样子:

name

1 个答案:

答案 0 :(得分:0)

能否请您检查一下是否可行:

import sys
import random,csv

def update(cells):
    d=""
    for cell in cells:
        d=d + str(cell)+","
    return d[:-1]

def update_score(name):
    with open('StudentNames&Questions.csv', 'r') as file:
        data = file.readlines()
    name_index = - 1
    score_index = -1
    headers = data[0]
    for index,header in enumerate(headers.split(",")):
        if header.strip() == 'Names':
            name_index=index
        if header.strip() == 'Score':
            score_index=index
    if name_index == -1 or score_index == -1:
        print "Headers not found"
        sys.exit()

    for index,row in enumerate(data):
        cells = row.split(",")
        if cells[name_index] == name:
            cells[score_index] = int(cells[score_index]) + 1
        data[index]=update(cells)

    with open('/Users/kgautam/tmp/tempfile-47', 'w') as file:
        file.writelines(data)


def NameGenerator():
    namelist_file = open('StudentNames&Questions.csv')
    reader = csv.reader(namelist_file)
    rownum=0
    global array
    array=[]
    for row in reader:
        if row[0] != '':
            array.append(row[0])
            rownum=rownum+1
    length = len(array)-1
    i = random.randint(1,length)
    name = array[i]
    return name


randome_name=NameGenerator()
update_score(randome_name)