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

如何使用Python从文本文件读取随机单个字符?(基于Raspberry Pi环境)

解决从文本文件读取随机字符并生成密码的问题

Hey Jeremy, let's fix up your code and get that random character selection working properly! First, let's go over the small issues in your current code, then jump to the corrected version.

你的现有代码里的几个问题

  • 忘记导入random模块——Python会找不到random.choice()函数,直接报错
  • contents = f.read少了括号,应该是contents = f.read()——不然contents只是指向read函数的引用,不是文件里的字符内容
  • 只在循环外选了一次random_character,导致生成的每个密码里所有字符完全一样,不是真正的随机
  • amnt(密码数量)和length(每个密码长度)未定义,需要先让用户输入或提前赋值

修正后的完整代码

import random

# 第一步:根据用户选择生成字符集并写入文件(改用with语句更安全,自动关闭文件)
chars = 'abcdefghijklmnopqrstuvwxyz'
ucchars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
smbls = '`¬!"£$%^&*()-_=+{[}]:;@~#<,>.?'
nos = '1234567890'
space = ' '

with open("selected.txt", "w") as f:
    usechars = input('Use lower case letters? answer y or n. ')
    if usechars.lower() == 'y':  # 用lower()兼容大写Y的输入,更友好
        f.write(chars)
    useucchars = input('Use upper case letters? answer y or n. ')
    if useucchars.lower() == 'y':
        f.write(ucchars)
    usesmbls = input('Use symbols? answer y or n. ')
    if usesmbls.lower() == 'y':
        f.write(smbls)
    usenos = input('Use numbers 0-9? answer y or n. ')
    if usenos.lower() == 'y':
        f.write(nos)
    usespace = input('Use spaces? answer y or n. ')
    if usespace.lower() == 'y':
        f.write(space)

# 第二步:获取用户想要的密码数量和长度
amnt = int(input('How many passwords do you want to generate? '))
length = int(input('How long should each password be? '))

# 第三步:读取字符集并生成随机密码
with open("selected.txt", "r") as f:
    char_set = f.read()  # 这里必须加括号,读取文件全部内容作为字符集

# 生成密码
for _ in range(amnt):
    password = ''
    for _ in range(length):
        # 每次循环都从字符集里随机选一个字符,保证真正随机
        password += random.choice(char_set)
    print(password)

更高效的优化版本(无需写入文件)

其实完全不需要把字符集写入文件再读取——直接在内存里拼接选中的字符集就行,省去磁盘IO操作,速度更快:

import random

chars = 'abcdefghijklmnopqrstuvwxyz'
ucchars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
smbls = '`¬!"£$%^&*()-_=+{[}]:;@~#<,>.?'
nos = '1234567890'
space = ' '

char_set = ''
usechars = input('Use lower case letters? answer y or n. ')
if usechars.lower() == 'y':
    char_set += chars
useucchars = input('Use upper case letters? answer y or n. ')
if useucchars.lower() == 'y':
    char_set += ucchars
usesmbls = input('Use symbols? answer y or n. ')
if usesmbls.lower() == 'y':
    char_set += smbls
usenos = input('Use numbers 0-9? answer y or n. ')
if usenos.lower() == 'y':
    char_set += nos
usespace = input('Use spaces? answer y or n. ')
if usespace.lower() == 'y':
    char_set += space

amnt = int(input('How many passwords do you want to generate? '))
length = int(input('How long should each password be? '))

for _ in range(amnt):
    # 用join+生成器表达式,比循环拼接字符串更高效
    password = ''.join(random.choice(char_set) for _ in range(length))
    print(password)

额外小建议

  • 可以加个判断:如果用户全选n导致char_set为空,就提示用户至少选择一种字符类型,避免random.choice()报错
  • 生成密码时用''.join()比循环+=更高效,尤其是密码较长的时候

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:54:42