【问题标题】:Password program: Writing password results to a file密码程序:将密码结果写入文件
【发布时间】: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


【解决方案1】:

在每个密码后写一个换行符:

f.write(passwd + '\n')

另外,你不应该这样做

f = open('pass.txt', 'r')

之前

f.close()

【讨论】:

  • 谢谢。你的建议奏效了!感谢您的帮助。
猜你喜欢
  • 2019-08-15
  • 1970-01-01
  • 1970-01-01
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-15
  • 1970-01-01
相关资源
最近更新 更多