如何用Python将列表写入文件?
我是Python的初学者,遇到了一个错误。我试图创建一个程序,将采取一个用户的用户名和密码,将他们写入列表,并将这些列表写入文件。以下是我的一些代码: 这是用户创建用户名和密码的部分如何用Python将列表写入文件?,python,list,file,pickle,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
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')
我的代码在这一点之前运行良好,在这一点上我得到了错误:
无效文件:
我不确定返回此错误的原因
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
是一个文件对象。要打开的第一个参数必须是文件名(io.open()
还支持文件描述符编号为int)。尝试将其参数强制为字符串
在您的情况下,这会导致
str(usernameFile) == '<_io.TextIOWrapper name='usernameList.txt' mode='wt' encoding='cp1252'>'
然后彻底清除
usernameFile
。你的想法是对的,但是有很多问题。当用户密码不匹配时,通常会再次提示输入这两个密码
with
块用于打开和关闭文件,因此无需在末尾添加close
下面的脚本显示了我的意思,您将有两个文件保存一个Python列表
。因此,尝试查看它没有多大意义,您现在需要将相应的读取部分写入代码
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也可能重复。如果用户输入了
password1
错误怎么办?您正在以两种模式同时打开文件wt
和wb
,我想wb
是这里的必备模式。谢谢,但即使在wb中完全打开文件,我仍然会得到错误:虽然循环有一个相当大的缺陷。它只要求确认密码。如果错误出现在第一个版本中,您将永远无法退出循环。感谢您的回答:)但是现在我面临一个“名称错误:名称“pickle”未定义”@Davina这是一个新问题,那么。也作为对未来问题的提示:当遇到此类错误时,发布完整堆栈跟踪始终是明智的,因为包含对首先导致问题的代码行的引用。
with open('usernameList.txt', 'wt') as f:
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)