[英]How do you write a list to a file in 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')
我的代碼可以正常工作,直到出現錯誤為止:
無效的文件:<_io.TextIOWrapper名稱='usernameList.txt'模式='wt'編碼='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()
有什么辦法可以解決該錯誤,或將列表寫入文件嗎? 謝謝
usernameFile=open('usernameList.txt', 'wt')
with open(usernameFile, 'wb') as f:
在第二行中, usernameFile
是一個文件對象。 open的第一個參數必須是文件名( io.open()
也支持文件描述符編號,以int表示)。 open()
試圖將其參數強制為字符串。
就您而言,這導致
str(usernameFile) == '<_io.TextIOWrapper name='usernameList.txt' mode='wt' encoding='cp1252'>'
這不是有效的文件名。
用。。。來代替
with open('usernameList.txt', 'wt') as f:
並完全擺脫usernameFile
。
您有正確的想法,但是有很多問題。 如果用戶密碼不匹配,通常您會再次提示輸入。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.