Python 密码程序:将密码结果写入文件

Python 密码程序:将密码结果写入文件,python,python-3.x,list,passwords,output,Python,Python 3.x,List,Passwords,Output,这是一个简单的程序,提示输入密码的长度以及要创建多少密码。我需要将结果打印到文件中。但是,它正在将所有结果打印到一行中。见下文 代码如下: import string import random print('''---Password Generator---''') characters = string.punctuation + string.ascii_letters + string.digits numofpasswd = int(input('How many passwords

这是一个简单的程序,提示输入密码的长度以及要创建多少密码。我需要将结果打印到文件中。但是,它正在将所有结果打印到一行中。见下文

代码如下:

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()
导入字符串
随机输入
打印('''---密码生成器--'''')
字符=字符串.标点符号+字符串.ascii字母+字符串.数字
numofpasswd=int(输入('您想要多少密码?:'))
passwdlength=int(输入('请选择字符数。选择超过8个字符以提高安全性:'))
如果passwdlength<8:
打印(“密码少于8个字符。请重新启动程序。”)
其他:
对于范围内的密码(numofpasswd):
passwd=''
对于范围内的字符(passwdlength):
passwd+=random.choice(字符)
打印(passwd)
f=打开(“pass.txt”,“a”)
f、 写入(passwd)
f=打开('pass.txt','r')
f、 关闭()
下面是一个示例输出。我请求了2个长度为9的密码:

~Lf>8ohcY

Q*tPR:

下面是写入pass.txt的内容:

~Lf>8ohcYQ*tPR:

如您所见,它结合了输出。请帮忙


额外:有没有一种方法可以简化这段代码?谢谢

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

f.write(passwd + '\n')
而且,你不应该这样做

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

f.close()

不要为每个密码重新打开文件。在循环之前打开它一次,写入所有密码,然后在循环之后关闭它。另外,修正你的缩进。谢谢。你的推荐成功了!我感谢你的帮助。