实验5 文件应用编程

with open('D://aa//data3.txt','r',encoding='utf-8')as f:
    data=f.read().split('\n')
    list1=data[1:11]
    print("原始数据:")
    print(list1)
list2=[]
for i in list1:
    num=float(i)
    y=int(num)
    x=num-y
    if x>=0.6:
        y+=1
        list2.append(y)
    else:
        y=y
        list2.append(y)
print("四舍五入后数据:")
print(list2)
with open('D://aa//data3_processed.txt','w',encoding='utf-8') as f:
    list1.insert(0,'原始数据')
    list2.insert(0,'四舍五入后数据')
    for i in range(len(list1)):
        f.write(f"{list1[i]}\t{list2[i]}\n")

Task3.py

with open('D://aa//data4.txt','r+',encoding='utf-8') as f:
    str=[i.strip('\n').split('\t') for i in f]
    a=str.pop(0)
    str.sort(key=lambda x : (x[2],-int(x[-1])))
    print('\t'.join(a))
    for i in str:
        print('\t'.join(i))
with open('D://aa//data4_progressed.txt','w') as f:
    f.write('\t'.join(a))
    f.write('\n')
    for i in str:
        f.write('\t'.join(i))
        f.write('\n')

Task4.py

task5.py

with open('D://aa//data5.txt', 'r', encoding='utf-8') as f:
    list=''.join([i for i in f])
    hang=len(list.splitlines())
    words=len(list.split())
    kong=list.count(' ')
    zifu=len(list)
    print('行数:',hang)
    print('单词数:',words)
    print('空格数:',kong)
    print('字符数:',zifu)
with open('D://aa//data5_with_line.txt','w',encoding='utf-8') as f:
    for i in range(hang):
        f.write('{} {}'.format(i+1,list.split('\n')[i]))
        f.write('\n')

 

posted @ 2022-05-13 18:31  琦哲  阅读(20)  评论(3编辑  收藏  举报