简体   繁体   English

如何在文本文件-Python中编写多个变量?

[英]How to write more than one variable in a text file - Python?

I am trying to create a Password Generator. 我正在尝试创建一个密码生成器。 The program is supposed to generate a List of random passwords and then write them to a .txt file. 该程序应生成随机密码列表,然后将其写入.txt文件。 With the code below, the program is only writing the last password generated, rather than all of them. 使用下面的代码,该程序仅写入最后一次生成的密码,而不是全部密码。

#!/usr/bin/python3
import random

#The Characters List
Characters = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()_+-=[];'\,./ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

#Password Generator

#Get the Input form the User
Length = input("Password Length > ")
Length = int(Length)

#Get the Input form the User
PasswordNumber = input("Number of Passwords > ")
PasswordNumber = int(PasswordNumber)

for p in range(PasswordNumber):
    Password = ""
    for i in range(Length):
        Password += random.choice(Characters)
    print(Password)

f= open("PasswordList.txt","w+")
f.write(Password)
f.close()

My results: 我的结果:

Password Length > 10
Number of Passwords > 5
LgoQ$i%e_O
![i/NxsqQr
n-ydWA/9.5
ksI,jg]#8q
![xrU#=2@#

But when I open the "PasswordList.txt" the text that is inside is only: ![xrU#=2@# , the last password it generated. 但是,当我打开“ PasswordList.txt”时,里面的文本只是: ![xrU#=2@# ,它生成的最后一个密码。 Also I want the passwords to have the same format as seen on the terminal: 我也希望密码具有与终端上相同的格式:

LgoQ$i%e_O
![i/NxsqQr
n-ydWA/9.5
ksI,jg]#8q
![xrU#=2@#

and not like this: 而不是这样:

LgoQ$i%e_O![i/NxsqQrn-ydWA/9.5ksI,jg]#8q![xrU#=2@#

You get only one password because that's what you told it to do: generate and print out all the passwords. 您仅获得一个密码,因为这就是您要执行的操作:生成并打印出所有密码。 Once they're all generated, then you write only one password to the file. 生成所有密码后,您只需在文件中写入一个密码。

You need to pull that print statement into your loop: 您需要将该打印语句放入循环中:

f = open("PasswordList.txt","w+")

for p in range(PasswordNumber):
    Password = ""
    for i in range(Length):
        Password += random.choice(Characters)
    print(Password)

    f.write(Password + "\n")

f.close()

To get the same format, simply add a newline to each write , or use the writeln method. 要获得相同的格式,只需在每个write添加一个换行符,或使用writeln方法。

Sample output, with 10 passwords of length 8: 示例输出,带有10个长度为8的密码:

w@wz+]S2
8t=G#r,F
H$aITs0&
=dMbird6
Y)Dpu]EZ
K\ZDNI*M
L6(2L_7_
VJL3GxF$
.nRt!XIa
=OXP8=aC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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