2013-03-15 61 views
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' 

的問題是:

計數字段值的數量[金額]更多大於或等於(9.79)

+0

哦喜,再次是你的,不是嗎?至少你這次有代碼。 :-) – 2013-03-15 20:50:10

+0

對不起,早些時候我有點急。 – user2173700 2013-03-15 20:50:43

+2

跳過第一行? – xbb 2013-03-15 20:51:09

回答

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) 
相關問題