Python注册登录测验系统开发求助:文件I/O报错问题
Fixing "I/O operation on closed file" Error in Your Quiz System Registration Code
What's Causing the Error?
Let's break this down simply: when you use a with statement to open a file, Python automatically closes that file as soon as you exit the indented block under the with. In your code, you first open userFile in a with block, write the username, then step out of that block—so userFile gets closed immediately. Later, when you try to write the year group and password using userFile.write(), the file is already shut down, hence that frustrating ValueError.
Corrected Code
Here's the fixed version of your code, with all operations that need to write to userFile contained within the same with block:
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) # Move all userFile-related operations inside the with block 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) # The reports.txt write stays here since it uses its own independent with block with open("reports.txt","a") as reports: reports.write("\n" + "Username:" + fullUsername) print "Your username is" + " " + (fullUsername)
Key Changes Explained
- All
userFileactions live in onewithblock: This keeps the file open for as long as you need to write to it, and Python takes care of closing it safely once you're done with all related tasks. - Rearranged the flow: Moved the year group input/validation and password input inside the
withblock so they can write touserFilewithout hitting a closed file error. - Kept
reports.txthandling separate: That's totally fine since it uses its ownwithblock, which manages that file's open/close cycle correctly.
Quick Extra Tips
- If you ever need to write to
user account .txtlater in your code (after closing it), you can re-open it with anotherwithstatement—use mode"a"instead of"w"if you don't want to overwrite existing user data. - For better security, consider adding password rules (like minimum length, mix of letters and numbers) to your registration flow.
内容的提问来源于stack exchange,提问作者user9215216
相关产品推荐
相关产品推荐

