如何在Python中从文本文件生成随机代码

2024-10-01 17:36:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了几行代码,能够从包含“abcdefghijklmnopqrstuvxyzabcdefghijklmnopqrstuvxyzabcdefghijklmnopqrstuvxyzo123456789”的文本文件(captcha.txt)中一次调用和打印一个符号<&书信电报;这是ASCII码

   import random
   import os
    
thisfolder = os.path.dirname(os.path.abspath(__file__))
captchatxt = os.path.join(thisfolder, 'captcha.txt')

with open(captchatxt) as text_file:
    captcha = text_file.read()
    random_word = random.choice(captcha)
    print (random_word)

但是,此代码一次只调用一个。我无法找到一种一次回忆6的方法,例如J64f7E。我设想的唯一方法是创建一个循环,编译这些随机字母/数字,并在循环结束时打印它们——我仍然无法实现这一点,任何解决方案都是非常有益的。谢谢

编辑:

import random 
import os
    
thisfolder = os.path.dirname(os.path.abspath(__file__))
captchatxt = os.path.join(thisfolder, 'captcha.txt')

with open(captchatxt) as text_file:
    captcha = text_file.read()
    print (''.join(random.choices(captcha, k=6)))

这个版本是有效的。谢谢大家。:)


Tags: path代码textimporttxtoswithrandom

热门问题