使用异常从Python中的文件读取数据

时间:2017-03-19 20:48:47

标签: python

我必须编写一个程序,它将从文件中读取数据,将其转换为整数并总计金额。到目前为止,这就是我所拥有的。数据文件“numdata.txt”中的数字是:78,93,85,100,81,76,94,77。

def main():
total = 0

try:
    NumberFile = open('numdata.txt', 'r')

    for line in NumberFile:
        amount = float(line)
        total += amount
        print(format(total, ',.2f'))

except IOError:
    print('An error occurred trying to read the file.')

except ValueError:
    print('Non-numeric data found in the file.')

except:
    print('An error has occurred.')

finally:
     NumberFile.close()


main()

当我运行程序时,显示第一个数字(78),然后出现一个异常错误消息,奇怪的是它有时会有所不同。如果有人可以帮我指出正确的方向,我会很感激。我还是很新,所以请耐心等待。

我尝试过但尝试过但无法使循环正常工作,所以我最终选择了这条路线:

def main ():
infile = open('numdata.txt', 'r')
num1 = int(infile.readline())
num2 = int(infile.readline())
num3 = int(infile.readline())
num4 = int(infile.readline())
num5 = int(infile.readline())
num6 = int(infile.readline())
num7 = int(infile.readline())
num8 = int(infile.readline())
infile.close()
total = num1+num2+num3+num4+num5+num6+num7+num8
average = total/8
print('the total: ', total)
print('the average: ', average)

main()的

它不漂亮,但它起作用我想lol

2 个答案:

答案 0 :(得分:0)

total = 0    

try:
    NumberFile = open('numdata.txt', 'r')

    for line in NumberFile:
        amount = float(line)
        total += amount
        print(format(total, ',.2f'))
except IOError:
    print('An error occurred trying to read the file.')
except ValueError:
    print('Non-numeric data found in the file.')
except:
    print('An error has occurred.')
finally:
    NumberFile.close()

发生异常是因为您在第一次迭代后立即关闭文件,导致您无法迭代其余部分。

NumberFile.close()移动到finally子句可确保文件被关闭,无论出现什么问题。但是,在Python中读取/写入文件的更好方法是使用with keyword,这是一种确保相同内容的内置方法。

total = 0

with open('numdata.txt', 'r') as f:
    for line in f:
        try:
            total += float(line)
        except ValueError:
            print('Non-numeric data found in the file.')
            continue
        finally:
            print('{:.2f}'.format(total, ',.2f'))

答案 1 :(得分:0)

您在第一次迭代中关闭文件NumberFile.close()没有正确缩进