CSV读取器未从数组中获取正确的值

2024-10-03 21:31:19 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我用来计算支票簿交易的一个类。我的问题在于elif语句,在这里我检查是row[0] == "starting"还是"ending"。在csv文件(我也将复制和粘贴)中,它在row[0]中清楚地声明这些单词在那里,但是我的startAmtendAmt在运行时都继续等于0

class Checkbook:
"""Checkbook class for list of check transactions"""

def __init__(self, filename):
    """initializer for Checkbook class"""

    self.name = filename
    self.debitList = []
    self.creditList = []
    self.startAmt = 0
    self.endAmt = 0.0

    with open(filename) as csvFile:
        readCSV = csv.reader(csvFile, delimiter = ',')

        for row in readCSV:

            try: 
                if (row[2] == " debit"):

                    debitAmt = row[3]
                    self.debitList.append(debitAmt)

                elif (row[2] == " credit"):

                    creditAmt = row[3]
                    self.creditList.append(creditAmt)

                elif (row[0] == "starting"):
                    self.startAmt += row[1]

                elif (row[0] == "ending"):
                    self.endAmt += row[1]

            except IndexError:
                pass

这是.csv文件:

starting, 1000
3/1/16, Valvoline, debit, 70.00
3/1/16, Panera Bread, debit, 12.59
3/4/16, ShopRite Groceries, debit, 100.69
3/5/16, Paycheck, credit, 248.39
3/10/16, Whole Paycheck Groceries, debit, 103.23
3/12/16, Fancy Restaurant, debit, 150.34
3/18/16, Burger King, debit, 8.34
3/19/16, Paycheck, credit, 248.39
3/23/16, ATM Withdrawal, debit, 40.0,
3/24/16, Whole Paycheck Groceries, debit, 248.39
3/28/16, Fancy Restaurant, debit, 112.34
ending, 651.36

如果有人知道为什么没有注册这些字符串,那么请让我知道


Tags: csvselfforendingfilenameclassrowstarting
3条回答

类文件: import csv class Checkbook(object): def __init__(self, filename): self.name =filename self.debitList = [] self.creditList = [] self.startAmt = 0 self.endAmt = 0.0 def Parse(self): with open(self.name) as csvFile: readCSV = csv.reader(csvFile, delimiter = ',') for row in readCSV: if (len(row) > 2): if (row[2] == " debit"): debitAmt = row[3] self.debitList.append(debitAmt) #print "debitlist"self.debitList elif (row[2] == " credit"): creditAmt = row[3] self.creditList.append(creditAmt) else: if (row[0] == "starting"): self.startAmt += int(row[1]) elif(row[0] == "ending"): self.endAmt += float(row[1]) return self.debitList,self.creditList,self.startAmt,self.endAmt类文件:

驱动程序文件:

import csvread obj=csvread.Checkbook("text.csv") db,cl,sa,ea=obj.Parse() print db,cl,sa,ea

首先转换为int

self.startAmt += int(row[1])

必须记住,从文件中读取的所有值都是字符串而不是数字。如果你想做计算,你必须智能地转换这些值

你也可以简化你的逻辑一点;同时,通过限制try/except块中的内容来改进代码。try块中的大型语句体在尝试调试问题时会导致问题

所以,让我们从读者总是会给你一个列表开始。如果列表中有两个元素,那么就知道它是起始/结束余额行。否则,它是一个显示完整事务详细信息的行

with open(filename) as csv_file:
    reader = csv.reader(filename, delimiter=',') # , is the default, so you
                                                 # can eliminate this
    for row in reader:
       if len(row) == 2:
          balance_type, value = row
          if balance_type == 'starting':
             self.start_amt += float(value)
          if balance_type == 'ending':
             self.end_amt += float(value)
       else:
          if len(row) == 4:
              trans_date, comment, trans_type, amount = row
              if trans_type == 'debit':
                  self.debit_list.append(float(amount))
              if trans_type == 'credit':
                  self.credit_list.append(float(amount))
          else:
             # We have some garbage data
             print('Invalid data {}'.format(row))

现在我们正在做一些显式检查,以避免在解析信息时出错

这看起来像是一些冗余代码,但每当您处理外部数据(如文件、用户输入、来自数据库或网络资源的信息)时,最好假设您将获得垃圾数据,并在检查/验证该数据时尽可能明确和彻底

相关问题 更多 >