【问题标题】:How do you write a list to a file in Python?如何在 Python 中将列表写入文件?
【发布时间】:2015-08-24 15:03:55
【问题描述】:

我是 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" 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()

有什么方法可以修复错误,或者有其他方法可以将列表写入文件吗? 谢谢

【问题讨论】:

  • Python: Write a list to a file 的可能重复项
  • 另外,你唯一的重试password2。如果用户输入password1 错误怎么办?
  • 你在wtwb两种模式下同时打开文件,我猜wb是这里必需的。
  • 谢谢,但即使在 wb 中完全打开文件,我仍然收到错误:
  • 那个while 循环有一个很大的缺陷。它只要求确认密码。如果错误出现在第一个版本中,您将永远无法退出循环。

标签: python list file pickle


【解决方案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)

【讨论】:

    【解决方案2】:
    usernameFile=open('usernameList.txt', 'wt')
    with open(usernameFile, 'wb') as f:
    

    第二行中的usernameFile 是一个文件对象。打开的第一个参数必须是文件名(io.open() 也支持文件描述符编号为整数)。 open() 尝试将其参数强制转换为字符串。

    在你的情况下,这会导致

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

    这不是一个有效的文件名。

    替换为

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

    并彻底摆脱usernameFile

    【讨论】:

    • 感谢您的回答 :) 但是现在我遇到了“NameError: name 'pickle' is not defined'
    • @Davina 那么这是一个新问题。也作为对未来问题的提示:遇到此类错误时,发布完整的堆栈跟踪总是明智的,因为其中包含对首先导致问题的代码行的引用。
    猜你喜欢
    • 1970-01-01
    • 2020-04-20
    • 2014-06-27
    • 2017-12-21
    • 1970-01-01
    • 2016-09-02
    • 2016-03-26
    • 2015-05-29
    • 2017-05-01
    相关资源
    最近更新 更多