- 读入一个Python程序,将其单行的注释(即 每一行“#”后面的内容)删除后保存;
代码:
def del_notes(py_filename,new_py_filename):
with open(py_filename) as f1,open(new_py_filename,'w') as f2:
for line in f1:
if not (line.strip()).startswith('#'):
f2.write(line)
print('')
del_notes('05_with.py','作业01.py')
运行结果:
- 随机生成100个学生的成绩保存在文件scores.txt文件中;
(1) 从文件中读出学生的成绩,输出最高、最低,以及平均成绩(平均成绩为小数)。
(2) 从文件中读出学生的成绩,统计90分以上学生的人数并输出。
(3) 求出这次考试的平均成绩,并统计各分数段的人数(优秀:≥90,良好:≥80,中等:≥70,及格:≥60,不及格:<60)。
(4) 将统计结果保存到数据文件statictic.txt中
代码:
import random
def creat_scores_file(filename):
with open(filename,'a+') as f:
for i in range(100):
f.write(str(random.randint(1,101)) +'\n')
creat_scores_file('scores.txt')
def fun1(filename):
with open(filename) as f:
li =[int(score) for score in f.readlines()]
avg_score = sum(li) / len(li)
max_score = max(li)
min_score = min(li)
return max_score, min_score, avg_score
def fun2(filename):
with open(filename) as f:
li = f.readlines()
excellent_score = [int(score) for score in li if int(score)>90]
return len(excellent_score),excellent_score
def fun3(filename):
with open(filename) as f:
li = [int(score) for score in f.readlines()]
count1,count2,count3,count4,count5 = 0,0,0,0,0
for score in li:
if score >= 90:
count1 += 1
elif score >= 80:
count2 += 1
elif score >= 70:
count3 += 1
elif score >= 60:
count4 += 1
else:
count5 += 1
count_dict = {
'优秀': count1,
'良好': count2,
'中等': count3,
'及格': count4,
'不及格': count5
}
return count_dict
def main(scoresfile,statisticfile):
a = fun1(scoresfile)
b = fun2(scoresfile)
c = fun3(scoresfile)
with open(statisticfile, 'a+') as f:
f.write(str(a)+'\n')
f.writelines(str(b)+'\n')
f.writelines(str(c)+'\n')
f.seek(0,0)
print(f.read())
main('scores.txt','statistics.txt')
运行结果:
生成文件:
scores.txt
statistics.txt