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()
计算Grade((是我教授所说的"霸主"功能。我正在尝试运行最低级和最高级功能中主要功能中拔出的文件,但它一直在给我o/i错误,我不确定该怎么做。
似乎在运行highestGrade()
后立即运行lowestGrade()
时,您似乎会发生错误。发生这种情况是因为您已关闭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
中截断代码。