简体   繁体   中英

Password program: Writing password results to a file

This is a simple program that prompts for the length of passwords, and how many passwords are to be created. I need to print the results to a file. However, it is printing all of the results into one line. See below.

Here is the code:

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()

Here is a sample output. I requested 2 passwords with a length of 9:

~Lf>8ohcY

Q* tPR :,

Here is what is written to pass.txt:

~Lf>8ohcYQ* tPR :,

As you can see, it combines the output. Please help.

extra: is there a way to simplify this code as well? Thanks!

Write a newline after each password:

f.write(passwd + '\n')

Also, you shouldn't do

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

before

f.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM