将输出写入csv文件时出现问题

时间:2016-04-27 23:35:15

标签: python csv math store

我已经分配了一项任务来记录数学测验的学生成绩

以下是我的任务:

老师想要使用学生参加这些测验的结果来记录他们的表现。系统应存储>每个学生的最后三个分数。

每次运行我的代码时,都没有数据添加到csv文件中,也就是"状态"文本文件保持为0,因此即使添加数据,分数也不会更新,而是附加到行

以下是我的代码:

import csv
import os

name = input("enter your name: ")
classroom_num = input("enter your classroom number: ")
score = 5
print ("%s, you scored %d/10 questions correctly"%(name,score)) 
status = open ("state.txt","w") #Every time program is run +1 is added, so that column 1-3 are updated
with open ("state.txt","r") as f:
    state = f.read()
    if os.stat("state.txt").st_size == 0:
        status.write ("0")

state_ints = [ int(x) for x in state.split() ] #converts into int
addone = 1
if state_ints == 3: #If program is run more than 3 times the value in text file reset to 0
    state_ints = 0
    status.write (state_ints)
with open("Classroom {}.csv".format(classroom_num),"a+") as f:
    rows = csv.reader(f)
    for row in rows:
        if row in rows in row[0] != (name) in row: #Checks if name exists in file (if so name isn't appended to column)
            state_ints.append(addone) #Adds one everytime program is run so that score can be replaced for row 1-3
            status.write (state_ints)
            name_row = (row [0])
            name_row.append(name)
            score_row = (row (state_ints))
            score_row.append(score)
        else:
            state_ints.append(addone)
            status.write (state_ints)
            score_row = (row [state_ints])
            score_row.append(score)
status.close()

2 个答案:

答案 0 :(得分:2)

在代码的第7行中,您以书写模式打开文件: status = open ("state.txt","w") 因此,该文件的内容(如果存在)将被删除。因此,第8-9行中的读取操作将无法读取任何内容:

with open ("state.txt","r") as f:
    state = f.read()

您可以阅读文件,进行更新,然后再将数据上传回文件。

答案 1 :(得分:1)

在写入文件之前,您正在重置state_ints。写入文件后执行此操作。或者你总是将0写入文件。