2016-04-27 160 views
-1

我被分配到記錄學生的分數爲數學測驗問題輸出寫入到CSV文件

下面一個任務是我的任務:

教師希望學生服用這些測驗使用的結果記錄他們的表現。系統應該爲每個學生存儲>最後三個分數。

每次我運行我的代碼時,沒有數據被添加到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() 

回答

1

你寫的文件之前,您正在重新設置state_ints。在寫入文件後執行此操作。或者你總是寫0到文件。

2

在代碼中的第7行讓你在寫作模式下打開一個文件: status = open ("state.txt","w") 使文件的內容,如果存在,是erased.Therefore在線路讀取操作8-9將找不到任何東西閱讀:

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

你可以讀你的文件,做你的更新,然後再上傳你的數據到文件。