1

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.

Davina
  • 37
  • 4
  • 1
    user_names and passwords are not files they are lists. you can just append to the list if you are just trying to add the inputs to the list – NendoTaka Aug 28 '15 at 21:41
  • The first argument to `open()` should be a file name, you're passing it a `list`. This [answer](http://stackoverflow.com/questions/4529815/saving-an-object-data-persistence-in-python/4529901#4529901) has examples. – martineau Aug 28 '15 at 21:51
  • 2
    Also, it's probably not a good idea to store passwords in an unencrypted file. – martineau Aug 28 '15 at 22:05
  • If you are using Python3, you definitely need to include a 'b' for binary. – Alex Huszagh Aug 29 '15 at 00:09
  • By the way, if you are using Python 2.7, use `import cPickle as pickle`. "cPickle is written in C, so it can be up to 1000 times faster than pickle" (https://docs.python.org/2/library/pickle.html). If you are using Python 3.x, just `import pickle`, and the program will try to import the optimized version automatically. – Electron Aug 29 '15 at 00:18

1 Answers1

1

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
zyxue
  • 7,904
  • 5
  • 48
  • 74