繁体   English   中英

将列表的输出保存到文件

[英]Saving the output of a list to a file

我遇到了一个面向像我这样的初学者的项目——创建一个 CLI 密码创建器。

我在一些指南的帮助下完成了生成器并添加了一些我自己的功能,但是有一个功能我似乎无法弄清楚如何实现; 将输出保存到文件中。

在终端中,密码逐行显示得非常好,但是如果我尝试将输出保存到文件中,它只会保存最后一个密码,并逐行分隔每个字母。

下面是我的代码,以及来自终端和 .txt 文件的输出示例。

import string
import random
from os import system, name


letters = list(string.ascii_letters)
digits = list(string.digits)
special_characters = list("!@#$%^&*()£")
characters = list(string.ascii_letters + string.digits + '!@#$%^&*()£')

def clear():
    if name == 'nt':
        _ = system('CLS')

    else:
        _ = system('clear')

def generate_random_password():

    clear()

    length = int(input("Enter password length: "))
    amount = int(input('Enter amount of passwords: '))

    letters_count = int(input("Enter letter count: "))
    digits_count = int(input("Enter digits count: "))
    special_characters_count = int(input("Enter special characters count: "))

    character_count = letters_count + digits_count + special_characters_count

    if character_count > length -1:
        print("Characters total count is greater than desired password length")
        exit()

    clear()

    password = []
    print("Following passwords saved to Passwords.txt, please move the file before generating new passords, as a new generation will overwrite existing")
    print('\n')

    for pwd in range(amount):
        password = []
        for c in range(digits_count):
            password.append(random.choice(digits))

        for c in range(letters_count):
            password.append(random.choice(letters))

        for c in range(special_characters_count):
            password.append(random.choice(special_characters))

        if character_count < length:
            random.shuffle(characters)
            for c in range(length - character_count):
                password.append(random.choice(characters))

                random.shuffle(password)


            if str(password) < str(length):
                return()
            else:
                print("".join(password))


            with open('Passowrds.txt', 'w') as file:
                for line in ("".join(password)):
                    file.write(line)
                    file.write('\n')

            #file = open('Passwords.txt', 'w')
            #str1 = repr(password)
            #file.write('\n' + str1 + '\n')
            #file.close
            #f = open('Passwords.txt', 'r')
            #if f .mode == 'r':
            #    contents=f.read

generate_random_password()

终端的输出如下所示:

Following passwords saved to Passwords.txt, please move the file
before generating new passords, as a new generation will overwrite
existing

gtBVA3QDcUohDc£TfX(zVt*24
KD8PnMD£)25hvHh#3xj79$qZI
Dx^*2£srcLvRx5g3B3(nq0H&9
&r6^3MEsaV1RuDHzxq*(h3nO)

然而,保存在 .txt 文件中的内容如下所示:

&
r
6
^
3
M
E
s
a
V
1
R
u
D
H
z
x
q
*
(
h
3
n
O
)

您的脚本仅保存 1 个密码的原因是因为您正在为您生成的每个密码打开要写入的文件(这会清除文件的内容)。

你想做一些类似的事情:

passwords = []
for _ in range(num_passwords):
    password = ...
    passwords.append(password)

with open("password.txt", "w") as f:
    f.writelines(passwords)

尽管您使用 random 库的方式没有什么可怕的,但我建议您查看random.sample (无替换)或random.choices (有替换)。

此外,使用改组您的characters列表不会为您的random.choice添加额外的随机性。

您不必为了运行选择将字符串转换为列表:

>>> import random
>>> random.choice("abc")
'b'

一个更完整的例子:

def generate_random_password():

    clear()

    length = int(input("Enter password length: "))
    amount = int(input("Enter amount of passwords: "))

    letters_count = int(input("Enter letter count: "))
    digits_count = int(input("Enter digits count: "))
    special_characters_count = int(input("Enter special characters count: "))

    character_count = letters_count + digits_count + special_characters_count

    if character_count > length - 1:
        print("Characters total count is greater than desired password length")
        exit()

    clear()

    passwords = []
    for _ in range(amount):
        chosen_digits = random.choices(digits, k=digits_count)
        chosen_letters = random.choices(letters, k=letters_count)
        chosen_special_characters = random.choices(
            special_characters, k=special_characters_count
        )

        extra_characters_count = length - character_count
        extra_characters = random.choices(characters, k=extra_characters_count)

        password = (
            chosen_digits
            + chosen_letters
            + chosen_special_characters
            + extra_characters
        )
        random.shuffle(password)
        passwords.append("".join(password))

    with open("Passwords.txt", "w") as f:
        f.writelines(passwords)

暂无
暂无

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

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