【问题标题】:Problems writing output to csv file将输出写入 csv 文件时出现问题
【发布时间】:2016-08-22 12:17:50
【问题描述】:

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

以下是我的任务:

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

每次我运行我的代码时,都不会将数据添加到 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()

【问题讨论】:

    标签: python csv math store


    【解决方案1】:

    在写入文件之前,您正在重置 state_ints。写入文件后执行此操作。否则您将始终将 0 写入文件。

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多