有没有更好的方法来忽略文件头?

时间:2019-10-17 07:57:09

标签: python python-3.x csv

我用python编写了一个读取代码文件的文件。但是我不喜欢使用next(iter)这样的方法来忽略标头。我需要一些建议来改进此代码。

文件格式:

OrderId, OrderName
1, Washing powder
2, Diaper
3, Cola
4, ToothPaste
5, Handfree

代码:

def set_order_details(self):

    order_record = self.order_file.readlines()

    iter_order = iter(order_record)
    next(iter_order) #For removing Headers

    for order_detail in iter_order:
        order_and_detail = order_detail.rstrip().split(',')

        if len(order_and_detail) == 2:
            self.order_dictionary[(order_and_detail[0])] = OrderDepth(order_and_detail[1])

    return self.order_dictionary


class OrderDepth:
    def __init__(self, order):
        self.order = order
        self.depth = 0

2 个答案:

答案 0 :(得分:0)

您有一个CSV format文件,因此使用内置csv.DictReader类的实例对其进行处理很有意义,并且可以通过自动跳过标头来简化代码并使代码更简单更具可读性。

还请注意,您根本不需要使用iter(),因为csv.DictReader实例就像文件一样已经可以迭代了。

由于您的示例代码不包含完整的类,因此我为演示目的组成了一个类,并在__repr__()类中添加了一个OrderDepth方法,以使其更易读。

import csv
from pprint import pprint


class OrderDepth:
    def __init__(self, order, depth=0):
        self.order = order
        self.depth = depth

    def __repr__(self):
        classname = self.__class__.__name__
        return f'{classname}(order={self.order!r}, depth={self.depth})'


class Foo:
    def __init__(self, filename):
        self.csv_file = open(filename, 'r', newline='')
        self.order_file = csv.DictReader(self.csv_file, skipinitialspace=True)

    def set_order_details(self):
        self.order_dictionary = {}
        for order_detail in self.order_file:
            if len(order_detail) == 2:
                od = OrderDepth(order_detail['OrderName'])
                self.order_dictionary[order_detail['OrderId']] = od
        return self.order_dictionary


foo = Foo("orders.csv")
order_dictionary = foo.set_order_details()
pprint(order_dictionary)

示例输出:

{'1': OrderDepth(order='Washing powder', depth=0),
 '2': OrderDepth(order='Diaper', depth=0),
 '3': OrderDepth(order='Cola', depth=0),
 '4': OrderDepth(order='ToothPaste', depth=0),
 '5': OrderDepth(order='Handfree', depth=0)}

答案 1 :(得分:-1)

def set_order_details(self):

        iter_order = iter(self.order_file.readlines()[1:])

        for order_detail in iter_order:
            order_and_detail = order_detail.rstrip().split(',')

            if len(order_and_detail) == 2:
                self.order_dictionary[(order_and_detail[0])] = OrderDepth(order_and_detail[1])

        return self.order_dictionary