随机验证码生成(python实现)
需求:生成随机不重复验证码。
代码:
#!/usr/bin/env python # encoding: utf-8 """ @author: 侠之大者kamil @file: 200number.py @time: 2016/4/13 23:33 """ import random,string def rand_str(num,length = 7): f = open("Activation_code2.txt","wb") for i in range(num): chars = string.ascii_letters + string.digits s = [random.choice(chars) for i in range(length)] f.write(bytes((''.join(s) + '\n' ), 'utf-8')) #f.write(''.join(s) + '\n') py2 f.close() if __name__=="__main__": rand_str(200)
会逐行写在文件里,涉及知识点:f.open f.writer random
#’str’ does not support the buffer interface 在python3 报错 with open("test.txt") as fp: line = fp.readline() with open("test.out", 'wb') as fp: fp.write(line) #解决方案1 在Python3x中需要将str编码, with open("test.txt") as fp: line = fp.readline() with open("test.out", 'wb') as fp: fp.write(bytes(line, 'utf-8')) #解决方案2 不想用b(binary)模式写入,那么用t(text, 此为写入的默认模式)模式写入可以避免这个错误. with open("test.txt") as fp: line = fp.readline() with open("test.out", 'wt') as fp: # with open("test.out", 'w') as fp: fp.write(line)
公众号请关注:侠之大者