import random import os.path def get_mobile_no(mobile_no_file_path): mobile_no ="" prifix =[135,136,137,138,150,159,188] while 1:
#随机选择一个开头 mobile_prifix =random.choice(prifix)
#随机生成后八位 mobile_postfix =random.randint(10000000,99999999)
#拼接 mobile_no =str(mobile_prifix)+str(mobile_postfix)
#判断文件是否存在 try: with open(mobile_no_file_path,"a+") as fp:
#判重逻辑 if mobile_no in fp.read(): continue
#写入文件 fp.write(mobile_no+" ") break except Exception as e: with open("no.txt","a+") as fp: if mobile_no in fp.read(): continue fp.write(mobile_no+" ") break return mobile_no print(get_mobile_no("d:\no2.txt"))
生成八位随机数也可以用zfill
Python zfill() 方法返回指定长度的字符串,原字符串右对齐,前面填充0。
代码改动:
import random import os.path def get_mobile_no(mobile_no_file_path): mobile_no ="" prifix =[135,136,137,138,150,159,188] while 1: mobile_prifix =random.choice(prifix) mobile_postfix =str(random.randint(0,99999999)).zfill(8)#从0开始,用zfill生成八位数 mobile_no =str(mobile_prifix)+str(mobile_postfix) try: with open(mobile_no_file_path,"a+") as fp: if mobile_no in fp.read(): continue fp.write(mobile_no+" ") break except Exception as e: with open("no.txt","a+") as fp: if mobile_no in fp.read(): continue fp.write(mobile_no+" ") break return mobile_no print(get_mobile_no("d:\no2.txt"))
遗留问题:用列表序列化做?