2017-06-06 64 views
-2

因此,我提出制作一个程序,该程序使用文本文件来存储密码以不忘记它们。该文本文件低于(password.txt的)Python文本文件附加错误

'Application1': ['Username1', 'Password1'] 
    'Application2': ['Username2', 'Password2'] 

所以,这个我想添加一个新行这将是: “Application3”:“USERNAME3”,“Password3”] 然而当我运行下面的代码时,它告诉我一个错误,说str不可调用。 (passwordsappend.py)

hp = open("Passwords.txt","a") #open the file 

    key = raw_input("Which app: ") 
    usr = raw_input("Username: ") 
    psw = raw_input("Password: ") #make variables to add 



    hp.write('\n\''(key)'\': ''[\''(usr)'\', ' '\''(psw)'\'],') #make it so that it's like the rest of the file 

    hp.close() #close the file 

我是想学习Python的代码来学习怎么样,但我看不出问题...谁能给我建议?

+0

你看起来像你可以使用一个很好的关于这个主题的ole教程。阅读[This](https://learnpythonthehardway.org/book/)书中练习6,7,8和9。这会给你一个更好的经典字符串处理的起点。你可能会遇到另一种没有提到的格式,那就是python字符串格式。这是一个更强大的格式化方法(f-字符串和'string.format()'),但是经典方法在语言间更为标准,因此需要知道。 – Aaron

回答

0

你的问题是当你试图写入文件。将其更改为

hp.write('\n\'' + key + '\': ''[\'' + usr + '\', ' '\'' + psw +'\']') 
2

如在一个不同的答案说,问题是你的字符串处理写入文件时。我会建议使用字符串格式化:

hp.write("\n'%s': ['%s', '%s']" % (key, usr, psw)) 

https://pyformat.info/

推荐码:

# Ask for variables to add 
key = raw_input("Which app: ") 
usr = raw_input("Username: ") 
psw = raw_input("Password: ") 

# Open file 
with open("Passwords.txt", "a") as hp: 
    # Add line with same format as the rest of lines 
    hp.write("\n'%s': ['%s', '%s']" % (key, usr, psw)) 

如果使用with open(...) as ...:你不必调用close方法,它自动调用当你退出with的范围。