首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将密码保存到python中的.txt文件中

将密码保存到python中的.txt文件中
EN

Stack Overflow用户
提问于 2020-06-04 02:31:55
回答 2查看 856关注 0票数 0

我正在自学python,我正在尝试创建一个密码生成器。我想要程序做的是,生成一个随机密码并将其保存到文本文件中。我在获取密码以保存到文本文件方面有什么问题。我能够获得一个生成的密码,但是我在text_file file.write( output ) NameError中得到了一个错误代码:虽然我已经定义了输出,但没有定义名称'output‘。如果有人能告诉我我做错了什么,我会很感激的。如果需要更多的信息,请告诉我。谢谢

代码语言:javascript
复制
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()

产出:

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-06-04 02:33:56

该函数中没有定义output。把它传进去,它就能用了。

票数 0
EN

Stack Overflow用户

发布于 2020-06-04 02:36:27

变量输出是局部变量。您需要将其定义为全局函数,或者使用参数将值传递给text_file函数。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62185913

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档