Read specific columns in csv using python

前端 未结 7 1382
耶瑟儿~
耶瑟儿~ 2021-02-06 06:27

I have a csv file that look like this:

+-----+-----+-----+-----+-----+-----+-----+-----+
| AAA | bbb | ccc | DDD | eee | FFF | GGG | hhh |
+-----+-----+-----+-----+---         


        
相关标签:
7条回答
  • 2021-02-06 07:16

    I think it will help.

    CSV

    1997,Ford,E350,"ac, abs, moon",3000.00
    1999,Chevy,"Venture ""Extended Edition""","",4900.00
    1996,Jeep,Grand Cherokee,"MUST SELL! air, moon roof, loaded",4799.00
    

    code

    import csv   
    
    def get_csv(file_name, names=None, usecols=None, mode='r', encoding="utf8",
                quoting=csv.QUOTE_ALL,
                delimiter=',',
                as_obj=False):
    
        class RowObject:
            def __init__(self, **entries):
                self.__dict__.update(entries)
    
        with open(file_name, mode=mode, encoding=encoding) as csvfile:
            data_reader = csv.reader(csvfile, quoting=quoting, delimiter=delimiter)
            for row in data_reader:
                if usecols and names:
                    q = dict(zip(names, (row[i] for i in usecols)))
                    yield q if not as_obj else RowObject(**q)
                elif usecols and not names:
                    yield list(row[i] for i in usecols)
                elif names and not usecols:
                    q = dict(zip(names, (row[k] for k, i in enumerate(row))))
                    yield q if not as_obj else RowObject(**q)
                else:
                    yield row
    

    example

    filename = "/csv_exe/csv.csv"
    vs = get_csv(filename, names=('f1', 'f2', 'f3', 'f4', 'f5'))
    for item in vs:
        print(item)
    

    result

    {'f1': '1997', 'f4': 'ac, abs, moon', 'f3': 'E350', 'f2': 'Ford', 'f5': '3000.00'}
    {'f1': '1999', 'f4': '', 'f3': 'Venture "Extended Edition"', 'f2': 'Chevy', 'f5': '4900.00'}
    {'f1': '1996', 'f4': 'MUST SELL! air, moon roof, loaded', 'f3': 'Grand Cherokee', 'f2': 'Jeep', 'f5': '4799.00'}
    

    example2

    vs = get_csv(filename, names=('f1', 'f2'), usecols=(0, 4))
    

    result2

    {'f1': '1997', 'f2': '3000.00'}
    {'f1': '1999', 'f2': '4900.00'}
    {'f1': '1996', 'f2': '4799.00'}
    

    example3

    vs = get_csv(filename, names=('f1', 'f2'), usecols=(0, 2), as_obj=True)
    

    result3

    <__main__.get_csv.<locals>.RowObject object at 0x01408ED0>
    <__main__.get_csv.<locals>.RowObject object at 0x01408E90>
    <__main__.get_csv.<locals>.RowObject object at 0x01408F10>
    
    for item in vs:
        print(item.f2)
    
    E350
    Venture "Extended Edition"
    Grand Cheroke
    
    0 讨论(0)
提交回复
热议问题