我是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()
有没有办法修复错误,或者用其他方法将列表写入文件? 谢谢
你的想法是对的,但有很多问题。当用户密码不匹配时,通常会再次提示输入这两个密码。你知道吗
with
块用于打开和关闭文件,因此不需要在末尾添加close
。你知道吗下面的脚本显示了我的意思,您将有两个文件保存一个Python
list
。因此,试图查看它将没有多大意义,您现在需要将相应的读取部分写入代码。你知道吗在第二行} 试图将其参数强制为字符串。你知道吗
usernameFile
是一个文件对象。open的第一个参数必须是文件名(io.open()
还支持文件描述符编号为int)。^{在你的情况下,这会导致
不是有效的文件名。你知道吗
替换为
彻底摆脱
usernameFile
。你知道吗相关问题 更多 >
编程相关推荐