实验6 文件应用编程2

#task3
def is_valid(x):
    if len(x)==18:
        if x.isdigit() or( x[:-1].isdigit() and x[-1]=='X'):
            return True
        else:
            return False
    else:
        return False

with open('data3_id.txt','r',encoding='utf-8')as f:
    data=f.readlines()
    a=[]
    for i in range(1,len(data)):
        if is_valid(data[i][3:-1]):
            a.append(data[i])
    a=sorted(a,key=lambda x:(x[-13:-9],x[-9:-7],x[-7:-5]))
    for i in a:
        print(f'{i[:2]},{i[-13:-9]}-{i[-9:-7]}-{i[-7:-5]}')

#task5_1
import random
import datetime
num=input('输入随机抽点人数:')
with open("data5.txt",'r',encoding='utf-8')as f1:
    a=f1.readlines()
    b=[i.strip('\n')for i in a]
    sam=random.sample(b,int(num))
    time=datetime.datetime.now()
    name=time.strftime('%Y%m%d') + '.txt'
    for i in sam:
        print(i)
with open(f'{name}','w',encoding='utf-8')as f2:
    for i in sam:
        f2.write(i+'\n')

#task5_2
print(f"{'抽点开始':=^40}")
import random
import datetime
t=datetime.datetime.now()
with open('data5.txt','r+',encoding='utf-8')as f1:
    data = f1.readlines()
    info = [line.strip('\n') for line in data]
while True:
    n=eval(input('输入随机抽点人数:'))
    if n==0:
        break
    with open(t.strftime('%Y%m%d')+ '.txt', 'a+', encoding='utf-8') as f2:
        info2 = random.sample(info, n)
        for i in info2:
            f2.write(i + '\n')
            info.remove(i)
            for j in i.split('\t'):
                print('%-5s\t' % j, end='')
            print()
print(f"{'抽点结束':=^40}")

 

posted @ 2022-05-23 21:43  孙艺欣  阅读(8)  评论(2编辑  收藏  举报