随机生成电话号码保存在txt中并按行读取
起因是这样的:
要求
1.奖池中电话号码通过文件输入,文件中每一行一个电话号码;
2.在控制台中每 100 毫秒在新行输出一个电话号码,模拟滚动效果;
3.用户单击回车键,停止滚动,输出中奖号码。
4.命令行:python lucky.py filename
a) lucky.py 为编写的 Python 代码文件;
b) filename 为奖池文件的路径;
c) 程序执行结果输出到控制台 stdout;
d) 处理文件不存在异常。
5.程序效果:
C:\temp>python lucky.py pool.txt
滚动开始(输入回车,滚动停止):
13155566543
…
中奖的号码为:15966668888
我手上没什么现成的能当奖池的文件,又觉得自己输入很麻烦,就先自己做一个随机生成的
import time
import random
import msvcrt
def modify_text():
with open('pool.txt', "r+") as f:
read_data = f.read()
f.seek(0)
f.truncate() #清空文件
def create_phone():
# 第二位数字
second = [3, 5, 7, 8][random.randint(0, 3)]
# 第三位数字
third = {3: random.randint(0, 9),
4: [5, 7, 9][random.randint(0, 2)],
5: [i for i in range(10) if i != 4][random.randint(0, 8)],
7: [i for i in range(10) if i not in [4, 9]][random.randint(0, 7)],
8: random.randint(0, 9), }[second]
# 最后八位数字
suffix = random.randint(9999999, 100000000)
# 拼接手机号
return "1{}{}{}".format(second, third, suffix)
# 生成手机号
modify_text()
for i in range(1,100):
phone = create_phone()
#print(phone)
with open('pool.txt', 'a') as fw:
fw.write(phone+"\n")
def txt2list():
# file 文件类型的对象
with open(rb'pool.txt') as file:
data = file.read().splitlines()
#print(data)
print(type(file))
print(file)
# # 以列表的形式输出文本
lines = list(data)
#print(lines)
# 输出文本的每一行
for eachLine in lines:
print(eachLine)
time.sleep(2)
if __name__ == "__main__":
txt2list()
可以随机生成电话号码,并保存在该目录下的pool.txt中,按行读取pool.txt,每行与下一行之间延时100毫秒,滚动输出。
抽奖程序的其他部分写完另外补一下,感觉这个稍微有点用,先记录一下
抽奖程序的整个:(可以达成要求)
import time
import random
import msvcrt
import sys
def modify_text():
with open('pool.txt', "r+") as f:
read_data = f.read()
f.seek(0)
f.truncate() #清空文件
def create_phone():
# 第二位数字
second = [3, 5, 7, 8][random.randint(0, 3)]
# 第三位数字
third = {3: random.randint(0, 9),
4: [5, 7, 9][random.randint(0, 2)],
5: [i for i in range(10) if i != 4][random.randint(0, 8)],
7: [i for i in range(10) if i not in [4, 9]][random.randint(0, 7)],
8: random.randint(0, 9), }[second]
# 最后八位数字
suffix = random.randint(9999999, 100000000)
# 拼接手机号
return "1{}{}{}".format(second, third, suffix)
# 生成手机号
modify_text()
for i in range(1,100):
phone = create_phone()
#print(phone)
with open('pool.txt', 'a') as fw:
fw.write(phone+"\n")
if __name__ == "__main__":
fo = open("pool.txt", "r+")
i = 0
N = 8
list = []
while i < 8:
list.append(fo.readline(50))
print(list[i],i)
i = i + 1
random.shuffle(list)
print("the random is \n")
for i in range(1, 8):
if msvcrt.kbhit():
k = msvcrt.getch()
if k in "\r\n":
break
else:
print(list[i]),
time.sleep(2) # 进程延迟命令,变量单位为秒
i = i + 1