Python I';我得到一个IO错误的代码,但它的工作。我不知道';我不明白

Python I';我得到一个IO错误的代码,但它的工作。我不知道';我不明白,python,Python,我刚刚为我的Python课程做了额外的工作,在这里和那里创建了一些小程序来提高我的技能。我编写了一个def,它要求输入用户名,检查文件,如果没有与给定用户名匹配的当前用户名,则将其写入文件。然后我写了一个新的def,然后请求一个PW,再次检查PW,并在给定的用户名后面写。唯一的问题是我得到了一个错误,但它仍然工作,并在名称后写入pw。你知道怎么解决这个问题吗 Traceback (most recent call last) File "C:blah blah dir to .py", line

我刚刚为我的Python课程做了额外的工作,在这里和那里创建了一些小程序来提高我的技能。我编写了一个def,它要求输入用户名,检查文件,如果没有与给定用户名匹配的当前用户名,则将其写入文件。然后我写了一个新的def,然后请求一个PW,再次检查PW,并在给定的用户名后面写。唯一的问题是我得到了一个错误,但它仍然工作,并在名称后写入pw。你知道怎么解决这个问题吗

Traceback (most recent call last)
File "C:blah blah dir to .py", line 72, in getnewpassword
    for line in settingpassword
ValueError: I/O operation on closed file
PW的def代码为

def getnewpassword(tempname):
    passwordPassed = False
    passwordComplete = False
    newpassword = raw_input('Please enter a password for ' + tempname + '.' + ' Please note that you cannot use spaces when creating a password.\n')
#makes sure there are no spaces in password.
    if ' ' in newpassword:
        print 'Sorry but your password has a space in it. Remember, you cannot have spaces in your password. Try again.\n'
        getnewpassword(tempname)
        passwordPassed = False
    else:
        print "Password accepted.\n"
        passwordPassed = True
#asks for password input again and checks to see if both password variables match.
    if passwordPassed == True:
        retypedpassword = raw_input('Please enter your password again.\n')
        if newpassword == retypedpassword:
            print "User account created."
            setuserpassword = retypedpassword
            passwordComplete = True
        else:
            print "passwords don't match. Please try again"
            getnewpassword(tempname)
#attempts to write password after username and :. works but gives an IO error.
    if passwordComplete == True:
        settingpassword = open('accounts.txt','r+')
        for line in settingpassword:
            if tempname in line:
                settingpassword.write(setuserpassword + '\n')
                settingpassword.close()

你在循环的第一次迭代中就关闭了文件谢谢,我修复了它!