我不确定为什么会收到此错误。我的程序中的一切似乎都运行良好。该程序基本上是一个简单的管理系统,用于存储用户名和密码帐户。
我得到的错误是,ValueError:对已关闭文件进行 I/O 操作。
程序成功写入第一个帐户,但其他帐户未存储在 .txt 文件中
这是我收到错误的代码
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...")
最佳答案
以下应该可以解决问题:
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...")
您在每次迭代后关闭文件,因为您只打开它一次,这就是只保存一个条目的原因。
使用 Python 的 with
结构也更安全,它会自动为您关闭文件。
如果您希望附加到现有文件,请使用“a”
作为模式。
关于python - 使用python 3.0输出文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32984571/