我正在尝试创建一个代码,用于检查用户是否已完成测验,以及他们是否会将他们的分数放在他们之前的分数旁边,如果他们还没有添加他们的名字和分数。 这是代码:
while count:
这是文本文件:
if userclass=="1":
with open("Class1scores.txt","a+",) as class1file:
lines = class1file.readlines() # all lines are stored here
for i,line in enumerate(lines):
if username in lines:
print("yes")
lines[i] = lines[i].strip() + ":" + str(score) + "\n"
else:
print("nope")
with open("Class1scores.txt","w",) as class1file:
class1file.write(str(username) + ":" + str(score))
class1file.write("\n")
class1file.seek(0)
for line in lines:
class1file.write(line)
class1file.close()
我希望它像:
Humzah:10
Humzah:0
Jack:10
它甚至不打印Yes nope所以我知道它与if语句有关但却不知道是什么? 在这里输入代码
答案 0 :(得分:4)
您的文件处理有点混乱。主要问题是您在写入模式下反复为不包含所需username
的行重新打开文件,用您编写的新内容破坏其当前内容。当文件已经在附加模式下打开时,你就是这样做的,这更令人困惑。 :)
我建议采用一种更简单的方法:将文件读入行列表,修改列表,然后编写修改后的列表。
请注意,您应该不 .close()
在with
声明中打开的文件:with
会自动关闭该文件阻止退出。
from __future__ import print_function
fname = "Class1scores.txt"
#username, score = "Humzah", 0
#username, score = "Jack", 10
username, score = "Humzah", 10
# Read current file data into a list of lines,
# discarding the newline at the end of each line
try:
with open(fname, "r") as f:
lines = f.read().splitlines()
except IOError:
#Create empty list if no file exists.
#This isn't totally robust, since other IO errors may occur.
lines = []
#Scan each line to see if contains the current `username`
for i, line in enumerate(lines):
if line.startswith(username):
print(username, "found on line", i)
lines[i] += ":" + str(score)
break
else:
#Control only gets here if we don't `break` out of the `for` loop
print(username, "not found; appending to list")
lines.append(username + ":" + str(score))
#Save modified list
data = "\n".join(lines) + "\n"
with open(fname, "w") as f:
f.write(data)