我想知道是否有人可以帮我弄清楚如何允许用户首先注册然后登录进行测验。我发现很难,因为用户的详细信息,如姓名,年龄和年份组以及用户名和密码需要保存到文本文件中。我已经完成了一些注册代码,但我仍感到困惑。
with open("user account .txt","w") as userFile:
usernamePart1 = raw_input("Enter your name:")
while not usernamePart1.isalpha():
print("Invalid name, try again")
usernamePart1 = raw_input("Enter your name:")
usernamePart2 = raw_input("Enter your age:")
while not usernamePart2.isdigit():
print("try again")
usernamePart2 = raw_input("Enter your age:")
fullUsername = usernamePart1[:3] + usernamePart2
userFile.write("Username:" + fullUsername)
with open("reports.txt","a") as reports:
reports.write("\n" + "Username:" + fullUsername)
print "Your username is" + " " + (fullUsername)
UserYearGroup = int(raw_input("Enter your year group:"))
while UserYearGroup < 7 or UserYearGroup > 15:
print("Invalid year group, enter again")
UserYearGroup = int(raw_input("Enter your year group:"))
if UserYearGroup >= 7 and UserYearGroup <= 14:
userFile.write("\nYear Group:" + str(UserYearGroup))
print(UserYearGroup)
password = raw_input("Enter a password which you will remember:")
userFile.write("\nPassword:" + password)
我跑的时候一直这么说:
Traceback (most recent call last):
line 22, in <module>
userFile.write("\nYear Group:" + str(UserYearGroup))
ValueError: I/O operation on closed file
答案 0 :(得分:0)
这行代码
userFile.write(“\nYear Group:” + str(UserYearGroup))
不在定义with
的{{1}}块中(第一个userFile
)。
一旦你离开with块,文件就会关闭,你就不能写了。
你可以:
with block
with
块中
例如:
userFile
或
with open("user account .txt","w") as userFile:
usernamePart1 = raw_input("Enter your name:")
while not usernamePart1.isalpha():
print("Invalid name, try again")
usernamePart1 = raw_input("Enter your name:")
usernamePart2 = raw_input("Enter your age:")
while not usernamePart2.isdigit():
print("try again")
usernamePart2 = raw_input("Enter your age:")
fullUsername = usernamePart1[:3] + usernamePart2
userFile.write("Username:" + fullUsername)
with open("reports.txt","a") as reports:
reports.write("\n" + "Username:" + fullUsername)
print "Your username is" + " " + (fullUsername)
UserYearGroup = int(raw_input("Enter your year group:"))
while UserYearGroup < 7 or UserYearGroup > 15:
print("Invalid year group, enter again")
UserYearGroup = int(raw_input("Enter your year group:"))
if UserYearGroup >= 7 and UserYearGroup <= 14:
userFile.write("\nYear Group:" + str(UserYearGroup))
print(UserYearGroup)
password = raw_input("Enter a password which you will remember:")
userFile.write("\nPassword:" + password)
以包装您的其他写入。