writelines在python中的用法Python作业五
作业五、⽂件操作
作业内容:
1、编写⼀个程序demo.py,要求运⾏该程序后,⽣成demo_new.py⽂件,其中内容与demo.py⼀样,只是在每⼀⾏的后⾯加上⾏号。要求⾏号以#开始,并且所有⾏的#垂直对齐。
2、假设某学校所有课程每学期允许多次考试,学⽣可随时参加考试,系统⾃动将每次考试的成绩都添加到Excel⽂件(包含3列:姓名、课程、成绩)中,现期末要求统计所有学⽣每门课程的最⾼成绩 。
编写程序,模拟⽣成若⼲同学的成绩 并写⼊Excel⽂件,其中学⽣姓名和课程名称均可重复,也就是允许出现同⼀门课程的多次成绩,最后统计所有学⽣每门课程的最⾼成绩,并写⼊新的Excel⽂件。
#5.1filename = ('C:/Users/Lenovo/Desktop/demo.py');#避免与转义字符混淆,这⾥⽤除号with open (filename ,'r') as fp :#以只读的⽅式打开该⽂件,with:⾃动关闭,⽂件中有汉字会导致编码出现问题 list1 = fp .readlines ();#从⽂件读取整⾏,可作列表使⽤,使⽤前提是open 模式为'r'mxlen = len (max (list1,key =len ));#长度为规则list1 = [line .rstrip ().ljust (mxlen )+'#'+str (index )+'\n'for index , line in enumerate (list1)];with open (filename [:-3]+'_new.py','w') as fp :#创建⽂件的格式:open(‘path’+filena
me+‘⽂件格式’,‘w’) fp .writelines (list1);#[:-3] 切⽚,截取filename ⽂件名的[0~-3]print (filename );#5.2import openpyxl ##对excel 操作import random def autodata (fileName ): #⽣成数据 wb = openpyxl .Workbook (); sheet = wb .active ; sheet .append (['姓名','课程','成绩']) first = tuple ('肖杨⾼唐谭沈'); middle = tuple ('⼆三四五六七⼋'); subjects = ('c++','data structure','python'); for i in range (500): line = [];#⼀⾏ name = random .choice (first )+random .choice (middle ); line .append (name ); line .append (random .choice (subjects )); line .append (random .randint (60,100)); sheet .append (line ); wb .save (fileName );def getMaxScore (oldfile ,newfile ): wb = openpyxl .load_workbook (oldfile ); final_wb = openpyxl .Workbook ();#⼤写创建excel start_sheet = wb .active ;#通过active 获取正在将使⽤的⼯作表 final_sheet = final_wb .active ; final_sheet .title = '学⽣各科成绩'; final_sheet .append (['姓名','课程','最⾼分']); stuGrade = {}#创建记录全校学⽣成绩的字典 for i in range (2,start_sheet .max_row +1): stuName =start_sheet ['A'+str (i )].value #获取学⽣名字,下同 lesName =start_sheet ['B'+str (i )].value #str()将对象转换成字符串 score =start_sheet ['C'+str (i )].value #获取excel 中的信息:sheet[列+⾏]列为⼤写英⽂字母,⾏为数字,但都是字符串 if stuName in stuGrade : stuGrade [stuName ]#do nothing else : stuGrade [stuName ] = {}; if lesName in stuGrade [stuName ]: if score >stuGrade [stuName ][lesName ]: stuGrade [stuName ][lesName ]=score ; else : stuGrade [stuName ][lesName ]=score ; #将最总成绩汇⼊新
表,按姓名有序,如果在此基础上课程有序应再加⼀循环访问课程 for student in stuGrade : for lesson ,score in stuGrade [student ].items (): final_sheet .append ([student ,lesson ,score ]); final_wb .save (newfile );oldfile = '成绩.xlsx';newfile = '最终成绩.xlsx';autodata (oldfile );getMaxScore (oldfile , newfile );1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论