Python文本文件附加错误

Python文本文件附加错误,python,python-2.7,Python,Python 2.7,因此,我被介绍制作一个程序,它使用一个文本文件来存储密码,以防忘记密码。文本文件如下。(Passwords.txt) 因此,我想在此基础上添加一行新内容,即: 'Application3':['Username3','Password3'] 然而,当我运行下面的代码时,它告诉我一个错误,说str是不可调用的。(passwordsapend.py) 我试图学习python代码来学习如何使用,但我看不出问题所在。。。有人能给我一些建议吗?你的问题是当你试图写入文件时。换成 hp.write('\n\

因此,我被介绍制作一个程序,它使用一个文本文件来存储密码,以防忘记密码。文本文件如下。(Passwords.txt)

因此,我想在此基础上添加一行新内容,即: 'Application3':['Username3','Password3'] 然而,当我运行下面的代码时,它告诉我一个错误,说str是不可调用的。(passwordsapend.py)


我试图学习python代码来学习如何使用,但我看不出问题所在。。。有人能给我一些建议吗?

你的问题是当你试图写入文件时。换成

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

正如在另一个回答中所说的,问题在于写入文件时的字符串处理。我建议使用字符串格式:

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

推荐代码:

# 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))

如果您将带有open(…)的
用作…:
您不必调用
close
方法,当您退出带有
范围的
时,它会自动调用。

您看起来可以使用有关该主题的好的“ole教程”。通读本书的练习6、7、8和9。这将为您提供一个更好的经典字符串处理起点。您可能会遇到这里没有提到的另一种格式,即python字符串格式。这是一种更强大的格式化方法(f-strings和
string.format()
),但经典方法在不同语言之间更为标准,因此需要了解。
hp.write("\n'%s': ['%s', '%s']" % (key, usr, psw))
# 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))