简体   繁体   English

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

[英]Reading Data from a File in Python with Exceptions

I have to write a program that will read data from a file, convert it to an integer and total the amount. 我必须编写一个程序,该程序将从文件中读取数据,将其转换为整数并总计。 So far here is what i have. 到目前为止,这就是我所拥有的。 The numbers from the data file "numdata.txt" are: 78,93,85,100,81,76,94,77. 数据文件“ 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()

When i run the program the first number (78) gets displayed and then one of the exception error messages comes up, the weird thing is that it's different sometimes. 当我运行程序时,显示第一个数字(78),然后出现一个异常错误消息,奇怪的是,有时它是不同的。 If someone could help point me in the right direction I'd appreciate it. 如果有人可以帮助我指出正确的方向,我将不胜感激。 I'm still very new to this so please bear with me. 我对此还很陌生,所以请多多包涵。

I tried and tried but could not get the loop to work correctly so i ended up going this route: 我试了又试,但是无法使循环正常工作,所以我最终选择了这条路线:

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() 主要()

It's not pretty but it works i guess lol 它不是很漂亮,但是我猜它可以正常工作

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()

The exception occurs because you're closing the file immediately after the first iteration, leaving you unable to iterate over the rest of it. 发生异常是因为您在第一次迭代后立即关闭了文件,从而使您无法遍历文件的其余部分。

Moving NumberFile.close() to a finally clause ensures the file is closed no matter what goes wrong. NumberFile.close()移至finally子句可确保无论发生什么问题都可以关闭文件。 However, a much better way to read / write files in Python is to use the with keyword , which is a built-in method of ensuring the same thing. 但是,在Python中读取/写入文件的一种更好的方法是使用with关键字 ,这是确保相同内容的内置方法。

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'))

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM