繁体   English   中英

python解析csv文件

[英]python parsing csv file

我正在解析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'

您的问题是s是一个整数,您将其初始化为0 然后,您尝试向其中添加一个字符串。 amount始终是一个字符串。 您无需执行任何操作即可将类似数字的数据转换为实际数字,它将始终是字符串。

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

s += float(amount)

PS:您应该使用stdlib中的csv模块读取CSV文件。

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

将始终打印“金额是数字”,因为您没有调用该方法(应为if amount.isdigit():

您可以确定通过从CSV文件中拆分一行而获得的任何字段都是字符串,您需要先将其转换为int:

s = s + int(amount)

s是一个int,而amount是一个数字的字符串表示形式,因此将s = s + amount更改为s += int(amount)

类似于?:(假设列标题为“ Year”,“ Month”,“ Day”,“ Amount”)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM