我的程序没有像我想要的那样运行。不检测文本文件

时间:2017-12-13 00:14:27

标签: python python-3.x

我是Python的初学者,我的代码没有正常工作。 我将代码放在与文本文件' hw.txt'

相同的目录中

这里用于txt:https://pastebin.com/vXuKeFCM

的pastebin

该程序应该取11个数字的平均数并删除最低数字。然后打印平均成绩。在进行异常处理时。但它只是继续跳过并直接进入除外线。即使文件在同一个地方。

#Welcome/Introduction Message
print("This program will read all the grades from the hw.txt file.")
print("Then the program wll calculate the final homework grade(average with the lowest grade dropped.")
print()

#TRY/ELSE/IF/STRUCTURE
try:
    file = open("hw.txt", "r")
    i = 0
    minGrade = 0
    total = 0
    for line in file:
        if i == 0:
            minGrade = int(line)
        else:
            if minGrade > int(line):
                minGrade= int(line)
        total = total + int(line)
        i = i + 1
    average = (total - minGrade)/(i-1)
    print("average final home grade:", average)
except:
    print("File cannot open or be found. Try troubleshooting.")

3 个答案:

答案 0 :(得分:0)

如果您删除try,则会收到此消息

ValueError: invalid literal for int() with base 10: '84.5\n'

正如您所看到的,84.5无法正确解析,因为它是double而不是int。你需要将它解析成一个浮点数

此外,拥有一个没有特定例外的try except是非常邪恶的。你将沉默所有异常而不是你想要的异常。

答案 1 :(得分:0)

要扩展我的评论,请按以下步骤重新构建代码,以便open块中只有try。请注意使用else块来指示在未发生错误时应执行的代码。

#Welcome/Introduction Message
print("This program will read all the grades from the hw.txt file.")
print("Then the program wll calculate the final homework grade(average with the lowest grade dropped.")
print()

#TRY/ELSE/IF/STRUCTURE
try:                  # try only to open the file
    file = open("hw.txt", "r")
except IOError:       # use a reasonably specific exception type
    print("File cannot open or be found. Try troubleshooting.")
else:                 # if no error occurred
    i = 0
    minGrade = 0
    total = 0
    for line in file:
        if i == 0:
            minGrade = int(line)
        else:
            if minGrade > int(line):
                minGrade= int(line)
        total = total + int(line)
        i = i + 1
    average = (total - minGrade)/(i-1)
    print("average final home grade:", average)

这将很快向您揭示实际问题(如Bobby所述)。

答案 2 :(得分:-1)

您收到此错误的主要原因是 文件 是Python中的关键字,因此通常的做法是使用 f 代替文件变量。

此外,如果更改文件变量,则仍会遇到int()问题。为什么使用int()来转换值?你想要向上或向下舍入?假设您不想舍入,我们可以简单地使用float()来获取所需的值。

另外,别忘了关闭文件!这是一个建议:

#Welcome/Introduction Message
print("This program will read all the grades from the hw.txt file.")
print("Then the program wll calculate the final homework grade(average with the lowest grade dropped.")
print()

#TRY/ELSE/IF/STRUCTURE
try:
    f = open("hw.txt", "r")
    i = 0
    minGrade = 0
    total = 0
    for line in f:
        if i == 0:
            minGrade = float(line)
        else:
            if minGrade > float(line):
                minGrade= float(line)
        total = total + float(line)
        i = i + 1
    average = (total - minGrade)/(i-1)
    print("average final home grade:", average)
except:
    print("File cannot open or be found. Try troubleshooting.")
finally:
    f.close()