7、假设有名为recordtxt的文件内容如下name age scoretom 12 86Lee 15 99Lucy 11 58Joseph 19 56第一栏为姓名name第二栏为年龄age第三栏为得分score请编写python程序完成以下任务:1读取文件;2输出得分低于60的人的姓名;3求出所有人的总分并输出
代码如下:
(1) 读取文件
with open("record.txt", "r") as f: lines = f.readlines()
(2) 输出得分低于60的人的姓名
for line in lines[1:]: # 从第二行开始遍历 data = line.strip().split() # 去除空格并分割成列表 if int(data[2]) < 60: print(data[0])
(3) 求出所有人的总分并输出
total_score = 0 for line in lines[1:]: data = line.strip().split() total_score += int(data[2]) print("总分为:", total_score)
(4) 姓名的首字母需要大写,判断record.txt 文件是否符合此要求,
若不符合,则纠正错误的地方。
for line in lines[1:]: data = line.strip().split() if not data[0][0].isupper(): # 判断首字母是否大写 correct_name = data[0].capitalize() # 将首字母大写 print("姓名错误:", data[0], "已更正为:", correct_name) line = line.replace(data[0], correct_name) # 替换原始行 lines[lines.index(line)] = line # 更新原始列表
将更正后的内容写回文件
with open("record.txt", "w") as f: f.writelines(lines
原文地址: https://www.cveoy.top/t/topic/g8Wy 著作权归作者所有。请勿转载和采集!