python解析csv文件

Avn*_*arr 1 python string parsing casting numbers

我正在解析一个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
Run Code Online (Sandbox Code Playgroud)

输出:金额是一个字符串金额是一个数字金额是一个字符串金额是一个数字

错误:

s = s + amount 
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Run Code Online (Sandbox Code Playgroud)

Ned*_*der 5

你的问题是它s是一个整数,你初始化它0.然后你尝试添加一个字符串.amount总是一个字符串.您没有做任何事情来将类似数字的数据转换为实际数字,它始终是一个字符串.

如果您希望金额为数字,则使用:

s += float(amount)
Run Code Online (Sandbox Code Playgroud)

PS:你应该使用csvstdlib中的模块来读取CSV文件.