Reputation: 55
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...")
Upvotes: 1
Views: 32
Reputation: 46759
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.
Upvotes: 1
Reputation: 6276
You should open the file for writing:
filehandle = open(filename, "w")
Upvotes: 0