# 实验六—文件应用编程2

 实验任务1： 1 def is_valid(x):
2     if len(x)==18:
3         if x[-1]=='Y':
4              return False
5         else:
6             return True
7     else:
8         return False
9
10 with open('C:\\Users\\可可子\\Desktop\\实验6数据文件\\data3_id.txt','r',encoding='utf-8') as f:
12     del data[0]
13     new=[]
14
15     for i in data:
16         datas=i.strip('\n').split(',')
17         if is_valid(datas[1]) == True:
18             new.append(datas)
19 new.sort(key=lambda x:int(x[1][6:10]))
20 for i in new:
21     print(f'{i[0]},{i[1][6:10]}-{i[1][10:12]}-{i[1][12:14]}')

 实验任务2： 1 import random
2 import datetime
3 f=open('C:\\Users\\可可子\\Desktop\\实验6数据文件\\data5.txt','r',encoding='utf-8')
4 t=datetime.datetime.now()
5 filename=t.strftime('%Y%m%d') + ('.txt')
6
7
8 with open(filename,'w',encoding='utf-8') as g:
10     x=int(input('输入随机抽点人数：'))
11     new_data=random.sample(data,x)
12
13 for i in new_data:
14     print(i.strip('\n'))
15
16 f.close()

 实验任务3： 1 print(f"{'抽点开始':=^40}")
2 import random
3 import datetime
4 f=open('C:\\Users\\可可子\\Desktop\\实验6数据文件\\data5.txt','r',encoding='utf-8')
5 t=datetime.datetime.now()
6 filename=t.strftime('%Y%m%d') + ('.txt')
7
8
9
10 a=[]
12 while True:
13     x=int(input('输入随机抽点人数：'))
14     if x==0:
15         break
16     else:
17         new_data=random.sample(data,x)
18         for i in new_data:
19             print(i.strip('\n'))
20             a.append(i)
21
22
23
24 print(f"{'抽点结束':=^40}")
25 f.close()
26
27
28
29 with open(filename,'w',encoding='utf-8') as g:
30     b=set(a)
31     for j in a:
32         g.write(j)

posted on 2022-05-19 19:38  张玮珊  阅读(11)  评论(2编辑  收藏  举报