繁体   English   中英

如何在Python中将列表写入文件?

[英]How do you write a list to a file in Python?

我是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名称='usernameList.txt'模式='wt'编码='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()

有什么办法可以解决该错误,或​​将列表写入文件吗? 谢谢

usernameFile=open('usernameList.txt', 'wt')
with open(usernameFile, 'wb') as f:

在第二行中, usernameFile是一个文件对象。 open的第一个参数必须是文件名( io.open()也支持文件描述符编号,以int表示)。 open()试图将其参数强制为字符串。

就您而言,这导致

str(usernameFile) == '<_io.TextIOWrapper name='usernameList.txt' mode='wt' encoding='cp1252'>'

这不是有效的文件名。

用。。。来代替

with open('usernameList.txt', 'wt') as f:

并完全摆脱usernameFile

您有正确的想法,但是有很多问题。 如果用户密码不匹配,通常您会再次提示输入。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM