代码不断出现错误

时间:2013-03-15 20:47:46

标签: python

代码不断出现错误。我试图修复错误,但它们仍然无法正常工作。我会再试一次解释这个问题。我有代码打开文件并阅读它。

数据位于Excel文件中。

amount (A1)
5.21 (A2)
4.63 (A3)
5.24 (A4)
3.62 (A5)
1.98 (A6)
16.47 (A7)
1.31 (A8)
1.85 (A9)
4.26 (A10)
0.98 (A11)
1.84 (A12)
0.51 (A13) 
15.58 (A14)
2.64 (A15)
4.32 (A16)
0.59 (A17)
0.21 (A18)
5.41 (A19)
0.08 (A20)
4.34 (A21) 

我试过

file=open ('3109336a.csv','r')

count = 0

with open('3109336a.csv', 'r') as f:
  values = f.readlines()

  for value in values:
    if float(value) >= 9.79:
      count += 1

print (count)

我不断得到的错误是:

Traceback (most recent call last):
  File "C:\Users\XXXX\Desktop\XXXXX\XXXX\studfiles\XXXXX\testing.py", line 9, in <module>
    if float(value) >= 9.79:
ValueError: could not convert string to float: 'amount, code, quant, val, number, tree\n'

问题是:

计算字段[amount]中的值的数量大于或等于(9.79)

1 个答案:

答案 0 :(得分:5)

如果您有CSV文件,请使用正确的工具进行阅读。使用csv module

import csv

with open('3109336a.csv', 'r', newline='') as f:
    reader = csv.reader(f)
    next(reader)  # skip the first row, it only contains headers.
    count = 0
    for row in reader:
        # row is now a *list* of columns.
        # I'll assume the *first* column is your value:
        amount = float(row[0])
        if amount >= 9.79:
            count += 1

    print(count)

这可以简化为:

with open('3109336a.csv', 'r', newline='') as f:
    reader = csv.reader(f)
    next(reader)  # skip the first row, it only contains headers.
    count = sum(1 for row in reader if float(row[0]) >= 9.79)

print(count)