首页 > 解决方案 > autograder 应该如何传递自己的文本文件?

问题描述

我编写了我的代码,我需要通过自动分级器,该自动分级器逐个输入其 ows 10 个文件以执行测试我需要在我的代码中更改什么,以便它将自动输入自己的文件 1 x 1。我应该如何编写文件输入代码部分?

我的代码

filename = input()

L = []
fileToProcess = open(filename, "r")
for line in fileToProcess:
   L.append(line.strip().split(' '))
#print(L)

lst2 = [item[0] for item in L]
# print(lst2)
mylist = list(set(lst2))
#print(mylist[0])

sum_1_M = 0
sum_1_W = 0
list_1 = []
count = 0
for i in range(len(mylist)):
    for x in L:
        if x[0] == mylist[i] and x[1] == 'M':
            sum_1_M += int(x[2])
            count = count + 1
        elif x[0] == mylist[i] and x[1] == 'W':
            sum_1_W += int(x[2])
            list_1.append(int(x[2]))
            list_1.sort()
    print('{} {} {} {}'.format(mylist[i], list_1[0], list_1[len(list_1) - 1], int(sum_1_M / count)))
    sum_1_M = 0
    sum_1_W = 0
    list_1 = []
    count = 0

输出

507 1000 1000 6
1 1400 1700 7

当我在自动评分器上运行代码时出现错误是这样的在此处输入图像描述

标签: python

解决方案


根据评论,我怀疑 Autograder 将文件名作为参数传递给您的程序,而不是手动或自动输入。用于sys.argv访问传入程序的参数。

最有可能的是,您需要这样做:

import sys

filename = sys.argv[1]

程序的其余部分保持不变。


顺便说一句,仅仅打开一个像这样的文件fileToProcess = open(filename, "r")并不是很好,因为您稍后没有关闭该文件并且没有隐式错误处理。正确的方法是:

with open(filename, "r") as fileToProcess:
    for line in fileToProcess:
        L.append(line.strip().split(' '))

这会在块之后关闭文件with,即使块内可能发生错误。


推荐阅读