如何用Python将列表写入文件?

2024-09-30 01:23:30 发布

您现在位置: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')

到目前为止,我的代码运行良好,我得到了错误:

invalid file: <_io.TextIOWrapper name='usernameList.txt' mode='wt' encoding='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()

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


Tags: txtinputyourifmatch错误passwordopen
2条回答

你的想法是对的,但有很多问题。当用户密码不匹配时,通常会再次提示输入这两个密码。你知道吗

with块用于打开和关闭文件,因此不需要在末尾添加close。你知道吗

下面的脚本显示了我的意思,您将有两个文件保存一个Pythonlist。因此,试图查看它将没有多大意义,您现在需要将相应的读取部分写入代码。你知道吗

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)
usernameFile=open('usernameList.txt', 'wt')
with open(usernameFile, 'wb') as f:

在第二行usernameFile是一个文件对象。open的第一个参数必须是文件名(io.open()还支持文件描述符编号为int)。^{}试图将其参数强制为字符串。你知道吗

在你的情况下,这会导致

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

不是有效的文件名。你知道吗

替换为

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

彻底摆脱usernameFile。你知道吗

相关问题 更多 >

    热门问题