【发布时间】:2020-06-10 00:53:02
【问题描述】:
这是一个简单的程序,它会提示输入密码的长度,以及要创建多少个密码。我需要将结果打印到文件中。但是,它将所有结果打印到一行中。见下文。
代码如下:
import string
import random
print('''---Password Generator---''')
characters = string.punctuation + string.ascii_letters + string.digits
numofpasswd = int(input('How many passwords would you like?: '))
passwdlength = int(input('Please pick amount of characters. Pick more than 8 characters for better security: '))
if passwdlength < 8:
print("Password is less than 8 characters. Please restart program.")
else:
for password in range(numofpasswd):
passwd = ''
for char in range(passwdlength):
passwd += random.choice(characters)
print(passwd)
f = open("pass.txt", 'a')
f.write(passwd)
f = open('pass.txt', 'r')
f.close()
这是一个示例输出。我请求了 2 个长度为 9 的密码:
~Lf>8ohcY
Q*tPR:,
这是写到 pass.txt 的内容:
~Lf>8ohcYQ*tPR:,
如您所见,它结合了输出。请帮忙。
额外:有没有办法简化这段代码?谢谢!
【问题讨论】:
-
不要为每个密码重新打开文件。在循环之前打开一次,写下所有密码,然后在循环之后关闭它。另外,修正你的缩进。
标签: python python-3.x list passwords output