错误:'错误的文件描述符'

时间:2016-04-28 12:06:06

标签: python

我不明白为什么在运行代码时出现以下错误消息:

with open(classChoice, 'r+') as resultfile:
OSError: [Errno 9] Bad file descriptor

这是我的代码:

import collections

classChoice = int(input("Which class do you want to order? "))
if classChoice == 1:
    open ("Class 1.txt")
elif classChoice == 2:
    open ("Class 2.txt")
else:
    open ("Class 3.txt")

scores = {}
def alphabetical():
    with open(classChoice, 'r+') as resultfile: 
        for line in resultfile:
            name, score = lines.split(":")
            scores.setdefault(name, collections.deque(maxlen=3)).append(int(score))

    for name in sorted(scores):
        m = max(scores[name])
        print('{name}: {m}'.format(name=name, m=m))

def highestScore():
    with open(classChoice, 'r+') as resultfile:
        for line in resultfile:
            name, score = line.split(":")
            scores.setdefault(name, collections.deque(maxlen=3)).append(int(score))

    for name in sorted(scores, key=lambda name: max(scores[name]), reverse=True):
        m = max(scores[name])
        print('{name}: {m}'.format(name=name, m=m))

def averageScore():
    with open(classChoice, 'r+') as resultfile:
        d = {}
        for line in resultfile:
            column = line.split(":")
            names = column[0]
            scores = int(column[1].strip())
            d.setdefault(names, []).append(scores)
        averages=[]

        for names, v in d.items():
            average = (sum(v[-3:])/len(v[-3:]))
            averages.append((names, average))
        for names, average in sorted(averages, key=lambda a: a[1], reverse=True):
            print(names, average)

orderChoice = (input("How do you want to order the data? "))
if orderChoice == "alphabetically":
                  alphabetical()
elif orderChoice == "with highest score for the tests, highest to lowest":
                  highestScore()
else:
                  averageScore()              

2 个答案:

答案 0 :(得分:0)

open需要一个字符串,你给它一个int。我想你要做的是

classChoice = int(input("Which class do you want to order? "))
if classChoice == 1:
    classChoice = "Class 1.txt"
elif classChoice == 2:
    classChoice = "Class 2.txt"
else:
    classChoice = "Class 3.txt"

答案 1 :(得分:0)

你的问题在这里:

Q
打开文件后,

classChoice = int(input("Which class do you want to order? ")) if classChoice == 1: open ("Class 1.txt") elif classChoice == 2: open ("Class 2.txt") else: open ("Class 3.txt") 将不执行任何操作。

但是,这里:

open ("Class <num>.txt")

您正试图打开with open(classChoice, 'r+') as resultfile: 。它是什么?我猜,它是classChoice12

  • 当您尝试打开某个号码时,您正在尝试打开文件描述符
  • 当你打开文件时,Python还为它创建了一个文件描述符 ......你真的不需要了解它现在是什么。

我建议您将代码更改为:

3

并改变以下几行:

classChoice = int(input("Which class do you want to order? "))
if classChoice == 1:
    filename = "Class 1.txt"
elif classChoice == 2:
    filename = "Class 2.txt"
else:
    filename = "Class 3.txt"

为:

with open(classChoice, 'r+') as resultfile: