Import Random Import the os.path DEF get_mobile_no (mobile_no_file_path): mobile_no = "" prifix = [135,136,137,138,150,159,188 ] the while . 1 :
# randomly selecting a beginning mobile_prifix = The random.choice (prifix)
# After eight randomly generated mobile_postfix = the random.randint (10000000 , 99999999 )
# splicing mobile_no = STR (mobile_prifix) + STR (mobile_postfix)
# determines whether a file exists the try : with Open (mobile_no_file_path, " A + ") as fp:
#判重逻辑 if mobile_no in fp.read(): continue
#写入文件 fp.write(mobile_no+"\n") break except Exception as e: with open("no.txt","a+") as fp: if mobile_no in fp.read(): continue fp.write(mobile_no+"\n") break return mobile_no print(get_mobile_no("d:\\no2.txt"))
Generating a random number can be used eight zfill
Python zfill () method returns a specified length of the original string right justified, padded with zeros in front.
Code changes:
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+"\n") break except Exception as e: with open("no.txt","a+") as fp: if mobile_no in fp.read(): continue fp.write(mobile_no+"\n") break return mobile_no print(get_mobile_no("d:\\no2.txt"))
Remaining problems: a list of serial overtaken?