实验5 文件应用编程

 
实验任务3:
 1 with open('data3.txt','r',encoding='utf-8') as f:  2     date=[]  3     for line in f.readlines():  4         line=line.strip()  5         date.append(line)  6 date.pop(0)  7 print('原始数据:')  8 print('['+','.join(date)+']')  9 with open('data3_processed.txt','w',encoding='utf-8') as f: 10      date1=[] 11      for i in date: 12         i=eval(i) 13         if i-int(i)<0.5: 14             i=int(i) 15         else: 16             i=int(i)+1 17         date1.append(i) 18      date.insert(0,'原始数据') 19      date1.insert(0,'四舍五入后数据') 20      for i in range(len(date)): 21         f.write(f{date[i]}\t{date1[i]}\n) 22 date1.pop(0) 23 print('四舍五入后数据:') 24 print(date1)
 实验任务4:
1 with open('data4.txt', 'r', encoding='utf-8') as f: 2 date=[] 3 for line in f.readlines(): 4 line=line.split() 5 date.append(line) 6 a=date.pop(0) 7 date2=sorted(date,key=lambda x:(x[2],-int(x[3]))) 8 with open('data4_processed.txt','w',encoding='utf-8') as f: 9 date2.insert(0,a) 10 for i in date2: 11 f.write('\t'.join(i)+'\n') 12 for j in i: 13 print('%-5s\t'%j,end='') 14 print()

 实验任务5:
1 with open('data5.txt', 'r', encoding='utf-8') as f: 2 list=''.join([i for i in f]) 3 hang=len(list.splitlines()) 4 words=len(list.split()) 5 kong=list.count(' ') 6 zifu=len(list) 7 print('行数:',hang) 8 print('单词数:',words) 9 print('空格数:',kong) 10 print('字符数:',zifu) 11 with open('data5_with_line.txt','w',encoding='utf-8') as f: 12 for i in range(hang): 13 f.write('{} {}'.format(i+1,list.split('\n')[i])) 14 f.write('\n')

 

实验总结:

1、学习了如何编写与文件有关的代码;

2、这次的实验比较综合,将前面几章的学习内容结合在一起,我运用的不是很熟练。