写入文本文档时,它不会提供所有给定的密码

时间:2019-01-01 20:46:53

标签: python python-3.x

我制作了一个密码生成器,该密码生成器按要求的数量和长度为我提供密码,我想将所有给定的密码保存到名为“ Your_Saved_Keys”的txt文档中,但是仅保存了一个生成的密码,而并非全部他们

import random
import time

print('''
Password Generator V2.0
=======================
''')

chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@£$%^&*().,? 
0123456789'

number = input('number of passwords? ')
number = int(number)

length = input('password length? ')
length = int(length)

print('''\nhere are your passwords: ''')

for pwd in range(number):
  password = ''''''
  for c in range(length):
    password += random.choice(chars)
  print(password)

save = input("""Do you want to save it to a txt file? Y/N""")

if save == "Y":
  format = ".txt"
  title = "Your_Saved_Keys"
  text_file = open(title + format, "w")
  text_file.write(password))
  print("Save Successful")

if save == "N":
  print("You Selected No")
print("-----------------------------------")
input("Press enter to exit")

3 个答案:

答案 0 :(得分:1)

您请求保存,并且在完成range(number)上的整个循环之后也要保存。因此,当然只保存最后生成的密码。

在循环之前询问并保存循环中的每个密码,或将所有密码保存在列表中,然后再保存列表。

答案 1 :(得分:1)

您的密码变量每次都会被覆盖。仅最后一个密码可用。您可以将所有密码保存到列表中,然后将其写入文件。该代码有效

import random
import time

print('''
Password Generator V2.0
=======================
''')

chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@£$%^&*().,?0123456789'

number = input('number of passwords? ')
number = int(number)

length = input('password length? ')
length = int(length)

passwords=[]
print('''\nhere are your passwords: ''')

for pwd in range(number):
  password=""
  for c in range(length):
      password+=random.choice(chars)
  passwords.append(password)
  print(password)

save = input("""Do you want to save it to a txt file? Y/N""")

if save == "Y":
  format = ".txt"
  title = "Your_Saved_Keys"
  with open(title + format, "w") as text_file:
      for password in passwords:
          text_file.write(password+'\n')
  print("Save Successful")

if save == "N":
  print("You Selected No")
print("-----------------------------------")
input("Press enter to exit")

答案 2 :(得分:0)

您正在将password变量写入文件。代码中的password变量将循环中最后一次生成的密码存储起来。

所以,要实现您想要的目标,

将生成的密码存储在列表中。 (在第一个循环中,在此列表中添加每个生成的密码)

然后将该列表的内容写入文件中。

注意:建议您对文件应用加密