[英]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.