python-3.x - 在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
解决方案
output
未在该函数中定义。把它传进去,它应该可以工作。
推荐阅读
- javascript - Rails 6 webpack 抛出“未捕获的 ReferenceError:$ 未定义”
- javascript - 如果那个或那个条件不满足,那么做
- reactjs - 如何使用 redux-saga 正确处理动作?
- c++ - 在 Gnome Builder 中使用库和头文件
- python - Spyder - 使用 sys.exit() 时内核死亡
- python - 这在 django 文档中关于基于类的视图是什么意思?
- python - 在 Django 中是否可以从第一个外键中获取一个字段?
- python-3.x - 如何比较两个列表并返回一个包含共享相同索引的元素的列表?
- c# - 如何获得 .NET 重定向以使用部署到具有 URL 后缀的 Azure API 管理服务的 API?
- python - 如何在python中找到基础扩展矩阵