Davina
Davina

Reputation: 37

Am I using pickle correctly?-Python

I am a beginner in Python and therefore am not sure why I am receiving the following error:

TypeError: invalid file: []

for this line of code:

usernamelist=open(user_names,'w')

I am trying to get an input of a username and password, write them to files, and then read them.

Here is the rest of my code:

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)

All answers would be appreciated. Thanks.

Upvotes: 1

Views: 306

Answers (1)

zyxue
zyxue

Reputation: 8820

Based on your script, this may help. It creates a 'username.txt' and 'password.txt' to store input username and password.

I use python2.7, input behaves differently between in python2.7 and 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

Upvotes: 1

Related Questions