def calculateGrades():
file = open(pickAFile(), "rt")
highestGrade(file)
lowestGrade(file)
def highestGrade (file):
lines= file.readlines()
file.close
len_lines_file = len(lines)
lines = lines[1:len_lines_file]
highest_Grade = 0.0
parts = lines[0].split(",")
highest_Grade = int(parts[2])
for line in lines:
parts = line.split(",")
if int(parts[2]) > highest_Grade:
highest_Grade = int(parts[2])
def lowestGrade(file):
open(file(, "rt")
lines= file.readlines()
file.close()
len_lines_file = len(lines)
lines = lines[1:len_lines_file]
lowest_Grade = 0.0
parts = lines[0].split(",")
lowest_Grade = int(parts[2])
for line in lines:
parts = line.split(",")
if int(parts[2]) < lowest_Grade:
lowest_Grade = int(parts[2])
print lowest_Grade
calculateGrade()
calculateGrade()是我教授所说的“霸主”功能。我试图在LowestGrade和highestGrade函数中运行主函数中提取的文件,但它一直给我O / I错误,我不知道该怎么做。
答案 0 :(得分:0)
当您在运行lowestGrade()
后尝试立即运行highestGrade()
时,似乎会出现错误。发生这种情况是因为您已在highestGrade()
中关闭了该文件,但未在lowestGrade()
中正确打开该文件:lowestGrade()
定义中的第一行应为file = open(pickAFile(), "rt")
。
通常,最好使用with
块打开文件,例如:
with open(pickAFile(), "rt") as file:
lines= file.readlines()
### file.close() is automatically called by Python at the end of the with block
所以一个选项是从highestGrade
和lowestGrade
函数中删除打开/关闭行,并在外面执行,比如说
def calculateGrades():
with open(pickAFile(), "rt") as file:
highestGrade(file)
lowestGrade(file)
但是,您可能需要考虑使用parts
作为lowestGrade
和highestGrade
的参数,并在函数外计算它:
def calculateGrades():
with open(pickAFile(), "rt") as file:
lines= file.readlines()
len_lines_file = len(lines)
lines = lines[1:len_lines_file]
parts = lines[0].split(",")
highestGrade(parts)
lowestGrade(parts)
并根据需要截断highestGrade
和lowestGrade
中的代码。