0

代码不断出现错误。我尝试修复错误,但它们仍然不起作用。我会尝试再次解释这个问题。我有打开文件并阅读它的代码。

数据在一个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) 的值的数量

4

1 回答 1

5

如果您有 CSV 文件,请使用正确的工具来阅读它。使用csv模块

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)
于 2013-03-15T20:51:48.127 回答