JES:关闭文件错误的I / O操作

时间:2017-05-03 05:21:14

标签: python jes

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错误,我不知道该怎么做。

1 个答案:

答案 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

所以一个选项是从highestGradelowestGrade函数中删除打开/关闭行,并在外面执行,比如说

def calculateGrades():
  with open(pickAFile(), "rt") as file:
    highestGrade(file)
    lowestGrade(file)

但是,您可能需要考虑使用parts作为lowestGradehighestGrade的参数,并在函数外计算它:

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)

并根据需要截断highestGradelowestGrade中的代码。