你如何用Python写一个文件列表?

时间:2015-08-24 15:03:55

标签: python list file pickle

我是Python的初学者并遇到了错误。我正在尝试创建一个程序,该程序将获取用户创建的用户名和密码,将它们写入列表并将这些列表写入文件。这是我的一些代码: 这是用户创建用户名和密码的部分。

userName=input('Please enter a username')

password=input('Please enter a password')

password2=input('Please re-enter your password')

if password==password2:

    print('Your passwords match.')

while password!=password2:

    password2=input('Sorry. Your passwords did not match. Please try again')

    if password==password2:

        print('Your passwords match')

我的代码工作正常,直到此时我收到错误:

  

无效文件:< _io.TextIOWrapper name ='usernameList.txt'mode ='wt'coding ='cp1252'>。

我不确定为什么会返回此错误。

if password==password2:
    usernames=[]
    usernameFile=open('usernameList.txt', 'wt')
    with open(usernameFile, 'wb') as f:
        pickle.dump(usernames,f)
    userNames.append(userName)
    usernameFile.close()
    passwords=[]
    passwordFile=open('passwordList.txt', 'wt')
    with open(passwordFile, 'wb') as f:
        pickle.dump(passwords,f)

    passwords.append(password)
    passwordFile.close()

有没有办法修复错误,或者将列表写入文件的其他方法? 感谢

1 个答案:

答案 0 :(得分:1)

你有正确的想法,但有很多问题。当用户密码不匹配时,通常会再次提示两者。

with块旨在打开和关闭您的文件,因此无需在末尾添加close

下面的脚本显示了我的意思,然后您将拥有两个持有Python list的文件。因此,尝试查看它没有多大意义,您现在需要将相应的读取部分写入您的代码。

import pickle

userName = input('Please enter a username: ')

while True:
    password1 = input('Please enter a password: ')
    password2 = input('Please re-enter your password: ')

    if password1 == password2:
        print('Your passwords match.')
        break
    else:
        print('Sorry. Your passwords did not match. Please try again')

user_names = []
user_names.append(userName)

with open('usernameList.txt', 'wb') as f_username:
    pickle.dump(user_names, f_username)

passwords = []
passwords.append(password1)

with open('passwordList.txt', 'wb') as f_password:
    pickle.dump(passwords, f_password)