Python:循环校验文件存在、main传文件名给readdata及计算平均分
问题与解决方案
我尝试校验当前目录下的文件是否存在,若存在则读取该文件,但代码存在问题。希望实现:
- 在while循环中校验文件是否存在并读取
- 从main函数向readdata传递文件名
- 计算文件中3名学生的平均分
原代码
import os.path def readdata(): isFileExist = False while isFileExist == False: userIN = str(input("Please Enter a file name, followed by .txt: ")) isExist = os.path.exists(userIN) if isFileExistExist == False: print(f"Checking... {userIN} DOES NOT exist in the current directory. Please retry.") else: print(f"Checking... {userIN} exist in the current directory.") print(f"\n The file < {userIN} > includes the following data:") IN = open(userIN,"r") std1N = IN.readline() std1M = IN.readline() std2N = IN.readline() std2M = IN.readline() std3N = IN.readline() std3M = IN.readline() IN.close() print(f" Student Name: {std1N.strip()}") print(f" Performance: {std1M.strip()} out of 100") print(f" Student Name: {std2N.strip()}") print(f" Performance: {std2M.strip()} out of 100") print(f" Student Name: {std3N.strip()}") print(f" Performance: {std3M.strip()} out of 100") print(f" The average exam score of the 3.0 students in the file < {userIN} > is {(eval(s1M.strip())+eval(s2M.strip())+eval(s3M.strip()))/3:.2f}.") def main(): readdata() if __name__ == '__main__': main()
修改后的完整代码
import os.path def readdata(filename): # 读取文件内容并收集学生数据 students = [] with open(filename, "r") as file: # 按姓名+分数的配对读取数据 while True: name_line = file.readline() score_line = file.readline() # 读到文件末尾或无有效数据时停止 if not name_line or not score_line: break name = name_line.strip() score = score_line.strip() if name and score.isdigit(): students.append({"name": name, "score": int(score)}) # 输出学生信息 print(f"\n The file < {filename} > includes the following data:") for student in students: print(f" Student Name: {student['name']}") print(f" Performance: {student['score']} out of 100") # 计算并输出平均分 if students: total_score = sum(student["score"] for student in students) average_score = total_score / len(students) print(f" The average exam score of the {len(students)} students in the file < {filename} > is {average_score:.2f}.") def main(): filename = "" is_file_exist = False # 在循环中校验文件存在性,直到输入有效文件 while not is_file_exist: filename = input("Please Enter a file name, followed by .txt: ") is_file_exist = os.path.exists(filename) if not is_file_exist: print(f"Checking... {filename} DOES NOT exist in the current directory. Please retry.") else: print(f"Checking... {filename} exists in the current directory.") # 将文件名传递给readdata函数 readdata(filename) if __name__ == '__main__': main()
关键实现说明
- 循环校验文件存在:把文件存在性判断逻辑放在main函数的while循环中,直到用户输入的文件存在才退出循环,确保后续处理的文件有效。
- main向readdata传递文件名:修改readdata函数,添加
filename参数,main函数在确认文件存在后,将文件名作为参数传入,避免使用全局变量,代码更规范。 - 计算平均分:
- 使用
with语句自动管理文件资源,无需手动关闭文件,避免资源泄漏。 - 用列表动态收集学生数据,即使文件中不是刚好3个学生也能兼容处理。
- 通过
sum()函数计算总分,除以学生数量得到平均分,替换原代码中错误的变量名和不安全的eval函数,直接将分数转为整数更安全可靠。
- 使用
- 修复原代码问题:修正了缩进错误、变量名拼写错误(如
isFileExistExist、s1M),优化了数据读取的容错逻辑。
内容的提问来源于stack exchange,提问作者noobatprogramming
相关产品推荐
相关产品推荐

