You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将随机生成的密码写入.txt文档?

随机密码生成器:添加保存到TXT文件功能及代码修复

先修正原代码中的两处错误:

  1. 字符集合定义错误:原代码把变量名当作字符串拼接,正确的做法是合并三个字符列表
  2. 数字生成循环计数错误:原代码误用了字母的计数来生成数字,导致数字数量和字母数量一致

以下是修复后并添加了保存到.txt文件功能的完整代码:

import random

letters = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
numbers = list("1234567890")
special_characters = list("!@#$%^&*()")
# 修复:合并三个字符列表,而不是拼接变量名字符串
characters = letters + numbers + special_characters


def generate_random_password():
    length = int(input("Enter password length: "))
    letter_count = int(input("How many letters do you want in your password? "))
    number_count = int(input("How many numbers do you want? "))
    special_character_count = int(input("How many special characters do you want? "))
    character_count = letter_count + number_count + special_character_count

    if character_count > length:
        print("Character count surpasses the set length, please try again.")
        return

    userpassword = []
    # 添加字母
    for i in range(letter_count):
        userpassword.append(random.choice(letters))
    # 修复:用number_count来控制数字生成数量
    for i in range(number_count):
        userpassword.append(random.choice(numbers))
    # 添加特殊字符
    for i in range(special_character_count):
        userpassword.append(random.choice(special_characters))

    # 补充剩余长度的随机字符
    if character_count < length:
        for i in range(length - character_count):
            userpassword.append(random.choice(characters))

    random.shuffle(userpassword)
    # 将密码转为字符串,方便后续操作
    final_password = "".join(userpassword)
    print(f"Generated password: {final_password}")

    # 保存到txt文件
    save_filename = input("Enter filename to save password (e.g., passwords.txt): ")
    # 使用with open自动管理文件资源
    with open(save_filename, "a", encoding="utf-8") as f:
        f.write(final_password + "\n")
    print(f"Password saved to {save_filename} successfully.")


generate_random_password()

关键修改说明:

  • 修复了characters列表的定义,确保包含所有可用字符
  • 修正数字生成循环的计数变量,匹配用户输入的数字数量
  • 将生成的密码转为字符串变量final_password,统一用于打印和保存
  • 添加文件保存逻辑,支持用户自定义文件名,采用追加模式("a")避免覆盖已有内容,同时指定编码为utf-8保证兼容性

内容的提问来源于stack exchange,提问作者Requiem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 12:15:47