[英]Python password protection code not writing to file
我試圖讓這段代碼在 Python 3.5.1 中工作,但我遇到了問題,它沒有將散列密碼和用戶名寫入指定的文件。 有什么我做錯了嗎?
import sys
import hashlib
import getpass
def main():
print ('\nUser & Password Storage Program v.01\n')
if input('The file will be modieifed if it exists.\nDo you wish to continue (Y/N): ') not in ('Y','y'):
sys.exit('\nChanges were not recorded\n')
user_name = input(str('Please Enter a User Name: '))
pwdinput = input("Now enter a password:").encode('utf-8')
password = hashlib.sha224(pwdinput).hexdigest()
try:
f = open(passfile.txt,'a+')
f.write(user_name + '\n')
f.write(password + '\n')
f.close()
except:
sys.exit('There was a problem writing to the file!')
print ('\nPassword safely stored in passfile.txt.\n')
main()
您沒有名為passfile.txt
的變量,這導致open
調用失敗。 如果用引號將文件括起來,它將正確打開文件,例如'passfile.txt'
這個語法錯誤不明顯的原因是因為你有一個包羅萬象的東西,你的程序只會打印“寫入文件時出現問題!” 反而。
與其使用except:
捕獲所有異常,不如使用except IOError:
的語法,因為只要在寫入文件時出現實際錯誤,就會拋出該語法。
錯誤是您的 open() 函數將對象作為參數,但您可能打算將其用作字符串。
此外,您通常應該在打開文件時使用with
塊。
try:
with open("passfile.txt",'a+') as f:
f.write("{}\n{}\n".format(user_name, password))
except Exception as e: # Use other exceptions for more accurate results
sys.exit('There was a problem writing to the file!\nError: {}'.format(str(e)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.