[英]Python quiz not writing to txt file
我正在嘗試編寫一個簡單的算術測驗。 用戶完成測驗后,我想將他們的姓名和分數記入文本文件。 但是,如果他們已經完成測驗,則應將他們的新分數附加在他們之前分數的同一行上。 當前文本文件包含:
Raju,Joyal : 10
但是,以相同的姓氏完成測試時,新分數不會添加到此行,並且以不同的姓氏完成測試時,根本不會將新行寫入文本文件。 這是我的代碼:
rewrite = False
flag = True
while flag == True:
try:
# opening src in a+ mode will allow me to read and append to file
with open("Class {0} data.txt".format(classNo),"a+") as src:
# list containing all data from file, one line is one item in list
data = src.readlines()
for ind,line in enumerate(data):
if surname.lower() in line.lower():
# overwrite the relevant item in data with the updated score
data[ind] = "{0} {1}\n".format(line.rstrip(), ", ",score)
rewrite = True
else:
src.write("{0},{1} : {2}{3} ".format(surname, firstName, score,"\n"))
if rewrite == True:
# reopen src in write mode and overwrite all the records with the items in data
with open("Class {} data.txt".format(classNo),"w") as src2:
src2.writelines(data)
flag = False
except IOError:
errorHandle("Data file not found. Please ensure data files are the in same folder as the program")
您正在打開文件,但是由於處於“追加”模式( a+
),因此您的讀/寫指針位於文件的末尾 。 因此,當您說readlines()
您什么也沒得到:即使文件不為空,也不會再有行超出當前位置。 結果,您的for
循環正在長度為0的列表上進行迭代,因此該代碼永遠不會運行。
您應該閱讀有關處理文件的內容(查找關鍵字seek
and tell
)。
請注意,即使您位於文件中間的正確位置,覆蓋現有文件中已經存在的內容也不是一個好方法:如果要寫入的數據與字節數不同您要覆蓋的內容會遇到問題。 相反,您可能需要打開該文件的一個副本以進行讀取,並創建一個新的副本來寫入。 當它們完成並關閉后,請移動較新的文件以替換較舊的文件。
最后請注意, if surname.lower() in line.lower()
不是水密邏輯。 如果您的文件的條目名為Raju,Joyal: 10
而其他人的姓為“ Joy”,該怎么辦?
這來自我自己的項目,但我不知道是否有幫助:
file=open("Mathematics Test Results (v2.5).txt","a")
file.write("Name: "+name+", Score: "+str(score)+", Class: "+cls+"."+"\n")
file.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.