实验5 文件应用编程
with open('data3.txt','r',encoding='utf-8') as f: data=f.readlines() f.close() with open('data3_proxessed.txt','w',encoding='utf-8') as b: a=['四舍五入后数据'] for i in range(len(data)): data[i]=data[i].strip('\n') for i in data[1:]: a.append(str(round(eval(i)))) for i in range(len(data)): b.write(data[i]+'\t'+a[i]+'\n') b.close() ys=[] zz=[] for i in data[1:]: i=eval(i.strip('\n')) ys.append(i) print(f'原始数据:\n',ys) for i in data[1:]: i=round(eval(i)) zz.append(i) print('四舍五入后数据:\n',zz)
with open('data4.txt', 'r+', encoding='utf-8')as f: a = [i.strip('\n').split('\t') for i in f] b = a[0] a.pop(0) a.sort(key=lambda x: (x[2], -int(x[-1]))) # 第三列升序,第四列降序 with open('data4_progressed.txt', 'w+', encoding='utf-8')as f: f.write('\t'.join(b) + '\n') for line in a: f.write('\t'.join(line)+'\n') with open('data4_progressed.txt', 'r', encoding='utf-8')as f: print(f.read())
with open('data5.txt','r',encoding= 'utf-8') as f: data = f.read() a = len(data.splitlines()) b = len(data.split()) c = 0 for i in data: if i == ' ': c += 1 d = len(data) print(f'行数:{a}') print(f'单词数:{b}') print(f'空格数:{c}') print(f'字符数:{d}') with open('data5_with_line.txt','w',encoding='utf-8') as f: for t in range(a): f.write(str(t+1)+' '+data.split('\n')[t]+'\n')