《Head First Programming》深入浅出程序设计 第5章
for循环与 文件close()和print()打印输出 的关系梳理
例题一:
文件results.txt中保存这些数据:
Johnny 8.65
Juan 9.12
Joseph 8.45
Stacey 7.81
Aideen 8.05
Zack 7.21
Aaron 8.31
需要:找到最高成绩,并打印输出。
涉及知识点包括:
1.open()函数:打开文件并且,赋值给文件句柄:result_f 。
2.for循环:for line in result_f 把文件中,每一行line进行迭代循环,找出最高分highest_score 。
3.多重赋值:(name,score) = line.split()
4.split()方法分割字符串 (name,score) = line.split()
5.文件close()和print()打印输出
写的时候,发现文件close()和print()顺序改变,输出成绩不一样,梳理一下:
![5faa60dd891f9eb84ae19f8f9056858a.png](https://img-blog.csdnimg.cn/img_convert/5faa60dd891f9eb84ae19f8f9056858a.png)
第一段代码,先关闭文件result_f.close(),然后进行print()输出,可以得到最高成绩 9.12。
highest_score = 0
result_f = open("results.txt")
for line in result_f:
(name,score) = line.split()
if float(score) > highest_score:
highest_score = float(score)
result_f.close()
print(highest_score)
第二段代码,先print()输出,然后关闭文件result_f.close(),得到两个成绩 8.65 和 9.12。
highest_score = 0
result_f = open("results.txt")
for line in result_f:
(name,score) = line.split()
if float(score) > highest_score:
highest_score = float(score)
print(highest