2012-07-17 107 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:你应该使用在STDLIB的csv模块读取的CSV文件。

0

s是一个整数,并且量是一个数字的字符串表示,所以改变s = s + amounts += int(amount)

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

将始终打印“量是一个数字”,因为你没有调用方法(它应该是if amount.isdigit():)。

你可以肯定,你从一个CSV文件拆分线得到任何领域将是一个字符串,你需要将其转换为int第一:

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