【发布时间】: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()
有什么方法可以修复错误,或者有其他方法可以将列表写入文件吗? 谢谢
【问题讨论】:
-
另外,你唯一的重试
password2。如果用户输入password1错误怎么办? -
你在
wt和wb两种模式下同时打开文件,我猜wb是这里必需的。 -
谢谢,但即使在 wb 中完全打开文件,我仍然收到错误:
-
那个
while循环有一个很大的缺陷。它只要求确认密码。如果错误出现在第一个版本中,您将永远无法退出循环。