Skip to main content
 首页 » 编程设计

python解析csv文件

2025年05月04日19lhb25

我正在解析一个 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 始终是一个字符串。您无需将类似数字的数据转换为实际数字,它始终是一个字符串。

如果您希望 amount 是一个数字,则使用:

s += float(amount) 

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