Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 有没有更好的方法来忽略文件中的标题?_Python_Python 3.x_Csv - Fatal编程技术网

Python 有没有更好的方法来忽略文件中的标题?

Python 有没有更好的方法来忽略文件中的标题?,python,python-3.x,csv,Python,Python 3.x,Csv,我用python编写了一个读取代码文件的文件,但我不喜欢我的方法,比如使用next(iter)忽略标题。我需要一些建议来改进这段代码 文件格式: OrderId,OrderName 1、洗衣粉 2、尿布 3、可乐 4、牙膏 5、免提 代码: def set\u order\u详细信息(self): iter\u order=iter(self.order\u file.readlines()[1:] 关于iter订单中的订单详情: order_和_detail=order_detail.rst

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

文件格式:

OrderId,OrderName
1、洗衣粉
2、尿布
3、可乐
4、牙膏
5、免提
代码:

def set\u order\u详细信息(self):
iter\u order=iter(self.order\u file.readlines()[1:]
关于iter订单中的订单详情:
order_和_detail=order_detail.rstrip().split(','))
如果len(订单和细节)==2:
self.order_dictionary[(order_和_detail[0])]=OrderDepth(order_和_detail[1])
返回self.order\u字典
您有一个文件,因此使用内置类的实例处理它是有意义的,它允许您通过自动跳过标题来简化代码,并且使代码更具可读性

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)
还要注意的是,您根本不需要使用
iter()
,因为与文件一样,
csv.DictReader
实例已经可以使用了

由于您的示例代码不包含完整的类,因此出于演示目的,我编写了一个类,并向
OrderDepth
类添加了
\uu repr\uu()
方法,以使打印它们更具可读性

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='洗衣粉',depth=0),
“2”:OrderDepth(order='Diaper',depth=0),
“3”:OrderDepth(order='Cola',depth=0),
“4”:OrderDepth(order='牙膏',depth=0),
“5”:OrderDepth(order='Handfree',depth=0)}

如果标题始终为一行且始终为第一行,则
next()
方法可以。(旁注:
.readlines()
调用可能是不必要的,您可以迭代文件句柄)为什么标记为
numpy
?python已经内置了,那你为什么要用一根树枝、一块石头和一根绳子拼凑你自己的锤子呢?@Aran Fey谢谢你通知我,我去掉了numpy的标签