2015-10-07 90 views
1

我不知道为什么我收到此错误。我的程序中的所有内容看起来都很完美。该程序基本上是一个简单的管理系统来存储用户名和密码帐户。错误输出文件与Python 3.0

我得到的错误是,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...")  

回答

1

以下应该解决的问题:

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"作为模式。

0

您应该打开要写入的文件:

filehandle = open(filename, "w")