2012-07-17 3 views
1

첫 번째 줄이 헤더 인 CSV 파일을 구문 분석하고 있습니다. 금액에 따라 금액을 합산하려고하지만 오류 메시지가 나타납니다. 디버깅하려면 열이 숫자인지, 오류 메시지에 따라 문자열인지 확인하는 중이며 둘 다입니다. 그 이유는 무엇일까요?python csv 파일을 구문 분석

def parseDataFromFile(self,f): 
    fh = open(f,'r') 
    s = 0 
    for line in fh: 
     #parsing the line according to comma and stripping the '\n' char 
     year,month,day,amount = line.strip('\n').split(',') 

     #checking the header row, could check if was first row as well - would be faster 
     if (amount == "Amount"): continue 

     #just for the debug checks 
     #here is the question 

     if isinstance(amount,str): 
      print "amount is a string" 
      #continue 
     if amount.isdigit: 
      print "amount is a digit" 

     #sum on the amount column 
     s = s + amount 

출력 : 금액은 문자열 양의 숫자 금액은 문자열 금액은 자리를입니다입니다

오류 :

s = s + amount 
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

답변

5

귀하의 문제는 s는 정수이다 이를 0으로 초기화합니다. 그런 다음 문자열을 추가하려고합니다. amount은 항상 문자열입니다. 숫자와 같은 데이터를 실제 숫자로 변환하는 일은 아무것도하지 않으며, 항상 문자열입니다.

당신이 금액은 수있을 것으로 예상하는 경우

후 사용

s += float(amount) 

PS를 : 당신이 CSV 파일을 읽기 위해 다음 stdlib에서 csv 모듈을 사용해야합니다.

0

의가 INT이며, 금액은 숫자의 문자열 표현이므로 변경 s = s + amounts += int(amount)

1
if amount.isdigit: 
    print "amount is a digit" 

항상이 메소드를 호출하지 않는 때문에 "양의 숫자는"인쇄합니다 (그것을 if amount.isdigit():이어야합니다.

당신은, 당신은 int로 처음으로 변환해야합니다 CSV 파일에서 라인을 분할하여 얻을 수있는 필드가 문자열을 될 것이라고 확신 할 수 있습니다 : 같은

s = s + int(amount) 
0

뭔가? (열 헤더가 "년", "월", "일", "금액"이라고 가정)

from collections import defaultdict 
import csv 

sum_by_ym = defaultdict(float) 
with open('input_file.csv') as f: 
    for row in csv.DictReader(f): 
     sum_by_ym[(row['Year'], row['Month'])] += int(float['Amount']) 

print sum_by_ym