首页 > 解决方案 > 在python中将密码保存到.txt文件

问题描述

我正在自学 python,我正在尝试创建一个密码生成器。我希望程序执行的操作会生成一个随机密码并将其保存到文本文件中。我在获取密码以保存到文本文件时遇到了麻烦。我能够生成密码,但我得到一个错误代码'在 text_file file.write(output) NameError: name 'output' is not defined',即使我已经定义了输出。如果有人能告诉我我做错了什么,我将不胜感激。如果我需要包含更多信息,请告诉我。谢谢

import random
import string

# Generates a password from random.choice
length = int(input('How long do you want your password? '))
x = (string.ascii_letters + string.digits + string.punctuation)

def password():
    for i in range(length):
        output = print(random.choice(x),end='')

# Saves password to text file
def text_file():
    print("Would you like to save your password to a text file?")
    answer = input('y/n: ')
    if answer == 'y':
        print("One moment...")
        file = open("Password.txt","a")
        file.write(output)
        file.close()
    if answer == 'n':
        print("...")
    else:
        print("Please input y or n...")


password()
print()
print()
text_file()

输出:

How long do you want your password? 18
lsR~P4Mj#K7xg3_]go

Would you like to save your password to a text file?
y/n: y
One moment...
Traceback (most recent call last):
  File "C:Password Generator.py", line 41, in <module>
    text_file()
  File "C:Password Generator.py", line 26, in text_file
    file.write(output)
NameError: name 'output' is not defined

标签: python-3.x

解决方案


output未在该函数中定义。把它传进去,它应该可以工作。


推荐阅读