Python--生成测试电话号码

生成指定数目的电话号码作为测试数据

方法1
#生成电话号码
def creat_phone_num(n):
import random
fp=open((‘e:\phone_num_’+str(n)+’.txt’),‘w’,encoding=‘utf-8’)
result=’’
for i in range(n):
result+=(str(random.randint(13000000001,13999999999))+’\n’)
fp.write(result)
fp.close()
return None

creat_phone_num(500)

方法2
#写一个可以生成手机号的函数,保证不能重复
def creat_phone_num(num):
phone_start=[137,138,139,136,135,133,130,131,132,158,159,156,151,152,153,157,189,188,187,186,185,183,177]
import random
phone_num_list=[]
count=num
while count>0:
phone_end=[]
for i in range(8):
s=random.choice(‘0123456789’)
phone_end.append(s)
end_num=’’.join(phone_end)
phone_num=str(random.choice(phone_start))+end_num
print(phone_num)
if phone_num not in phone_num_list:
phone_num_list.append(phone_num)
count-=1
else:
continue
print(phone_num_list)
count1=len(phone_num_list)
print(‘生成了%s个号码’ %count1)
return phone_num_list

#生成X个手机号,要求不能重复,写到文件中
#先写到列表中,再写到文件中
def creat_phone_num_in_file(file_path,file_name,num):
#num=int(input(‘请输入生成多电话号码的个数:’))
import os.path
if not isinstance(file_path,str) or not os.path.exists(file_path):
print(‘输入路径不正确’)
return None
if not isinstance(file_name,str) or not (’.txt’ in file_name):
print(‘非.txt文件’)
return None
if (not isinstance(num,int)) or num<=0:
print(‘输入为非正整数类型’)
return None
try:
with open(file_path+’\’+file_name,‘w’,encoding=‘utf-8’) as fp :
fp.writelines(list(map(lambda x:x+’\n’,creat_phone_num(num))))
print(‘写入文件%s成功,文件类型为utf-8’%(file_path+’\’+file_name))
return None
except Exception as e:
print(e)
with open(file_path+’\’+file_name,‘w’,encoding=‘gbk’) as fp :
fp.writelines(list(map(lambda x:x+’\n’,creat_phone_num(num))))
print(‘写入文件%s成功,文件类型为gbk’%(file_path+’\’+file_name))
return None

你可能感兴趣的:(个人python小程序)