我是否正确使用泡菜?-Python

Am I using pickle correctly?-Python

我是 Python 的初学者,因此不确定为什么会收到以下错误:

TypeError: invalid file: []

对于这行代码:

usernamelist=open(user_names,'w')

我正在尝试获取用户名和密码的输入,将它们写入文件,然后读取它们。

这是我的其余代码:

user_names=[]
passwords=[]
username=input('Please enter a username')
password=input('Please enter a password')
usernamelist=open(user_names,'w')
pickle.dump(userName,usernamelist)
usernamelist.close()
usernamelist=open(user_names,'r')
loadusernames=pickle.load(usernamelist)

passwordlist=open(passwords,'w')
pickle.dump(password,passwordlist)
passwordlist.close()
passwordlist=open(passwords,'r')
loadpasswords=pickle.load(passwordlist)

所有答案将不胜感激。谢谢

根据您的脚本,这可能会有所帮助。它创建一个 'username.txt' 和 'password.txt' 来存储输入的用户名和密码。

我使用 python2.7,python2.7 和 python3.x 中的输入行为不同。

"""
opf: output file
inf: input file

use with instead of .open .close: http://effbot.org/zone/python-with-statement.htm

for naming rules and coding style in Python: https://www.python.org/dev/peps/pep-0008/
"""


import pickle

username = raw_input('Please enter a username:\n')
password = raw_input('Please enter a password:\n')

with open('username.txt', 'wb') as opf:
    pickle.dump(username, opf)

with open('username.txt') as inf:
    load_usernames = pickle.load(inf)
    print load_usernames

with open('password.txt', 'wb') as opf:
    pickle.dump(password, opf)

with open('password.txt') as inf:
    load_passwords = pickle.load(inf)
    print load_passwords