1

I am not sure why I am receiving this error. Everything in my program seems to be working perfectly. the program is basically a simple administration system to store username and password accounts.

the error i get is, ValueError: I/O operation on closed file.

the program successfully writes the first account, but the other accounts do not get stored in the .txt file

here is my code where i am getting the error

if savedata == 'y': 
print ("\nData Successfuly Saved!")
filehandle = open(filename, "r+")

    for username, password in store_data.items():
        print(username, ":",password)
        password = password.replace("\n","")
        filehandle.write(username) # it says this line is my error
        filehandle.write(":") 
        filehandle.write(password)
        filehandle.write("\n")
        filehandle.close()  

   else:
 ("Exiting Application Terminal...")    

2 Answers 2

1

The following should fix matters:

if savedata == 'y': 
    print ("\nData Successfully Saved!")

    with open(filename, "w") as filehandle:
        for username, password in store_data.items():
            print(username, ":", password)
            password = password.replace("\n","")
            filehandle.write("{}:{}\n".format(username, password))
else:
    print("Exiting Application Terminal...") 

You were closing the file after each iteration, as you only opened it once, this is why only one entry was saved.

It is also safer to use Python's with construct which will automatically take care of closing the file for you.

If you wish to append to an existing file, use "a" as the mode.

Sign up to request clarification or add additional context in comments.

Comments

0

You should open the file for writing:

filehandle = open(filename, "w")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.