当分数大于3时,我的代码试图删除文本文件中最早的分数。这是文本文件:
humzah:0:6:5
ikrah:8:6:4
这是我的代码:
if userclass=="1": #if userclass is equal to 1
with open ("Class1scores.txt", "r") as dataforclass1:#open the class 1 file as
#data for class 1 in read plus mode
lines = dataforclass1.read().splitlines() #lines is equal to each line on
#the file (list).
for lineno1, line in enumerate(lines): #for the line number
usertaken=input("Have you taken this quiz before, yes or no") #first ask if the user
#has done this quiz before
while True: #this states that while it is true
if usertaken=="yes": #if the user says yes continue the script
break
if usertaken=="no": #if the user says no continue the script
break
else:
print("That is not a valid answer! yes or no")#if the user
continue
if usertaken=="yes": #if they have then find the line and add to it
if line.startswith(username):
print("was found on line", lineno1) #tells the user what lines their name is on
lines[lineno1] += ":" + str(score)
break
else:
lines.append(username + ":" + str(score)) #if they have not add to
#a new line
break
data = "\n".join(lines) + "\n" #data is the list plus indents (\n means new
#line)
with open("Class1scores.txt", "w") as file: #opens the file in write mode
file.write(data) #this writes in to the file
print(data)
with open('Class1scores.txt','r') as class1file:#with the text file
#as class1file
lines = []#this creates an empty list
for x, line in enumerate(class1file):#to find x read the lines
if lineno1==x:
class1_list = line.split(':')#split the text file by :
if len(class1_list) > 4:#if theres more than 4 values
del class1_list[1]#delete the first score
line = ':'.join(class1_list)#the line is equal to the
#data with : as the seperator
lines.append(line)#append this to the list
with open("Class1scores.txt",'w') as writefile:
writefile.write(''.join(lines))
对于1级,它只是循环问题"你在#34;之前进行了这个测验吗?对于其他类,复制和粘贴相同的代码,它表示" lineno1未定义"。有什么帮助吗?
答案 0 :(得分:0)
lineno1仅在if-block中定义,其中userclass等于1.在所有其他情况下,变量永远不会被定义,因此会抛出错误。
如果在代码的第一行定义lineno1,它将在第一个if块中被覆盖,但你也可以在第二个if块中使用。