標籤:
需求:產生隨機不重複驗證碼。
代碼:
#!/usr/bin/env python# encoding: utf-8"""@author: 俠之大者kamil@file: 200number.py@time: 2016/4/13 23:33"""import random,stringdef 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)
隨機驗證碼產生(python實現)