简体   繁体   English

如何处理每行可变列的CSV

[英]How to handle CSV with variable columns per row

I've got a file that has a header row with a fixed number of labels and rows of variable length. 我有一个文件,该文件的标题行具有固定数量的标签和可变长度的行。 The last column has a field that should really be a sublist of items, but this list is treated as a continuum of columns. 最后一列具有一个字段,该字段实际上应该是项目的子列表,但是此列表被视为列的连续体。

Example: 例:

Name, Address, Telephone
"Bob Smith", "123 main st", "111-111-1111"
"Jon Smith", "123 main st", "111-111-1111", "222-222-2222"

I ultimately want to iterate over the sublist, in this case telephone #'s. 我最终想遍历子列表,在这种情况下是电话号码。

I've tried using csv dictreader but it drops the extra columns. 我试过使用csv dictreader,但它会删除多余的列。

Thanks in advance. 提前致谢。

As you can see in DictReader docs : 如您在DictReader docsDictReader

If a row has more fields than fieldnames , the remaining data is put in a list and stored with the fieldname specified by restkey (which defaults to None ). 如果一行中的字段多于fieldnames ,则剩余数据将放入列表中,并以restkey指定的字段名存储(默认为None )。

All you must do is pass the restkey parameter and all your extra values will go there. 您所要做的就是传递restkey参数,您所有的restkey都将到达该位置。

with open('yourfile.csv') as f:
    cf = csv.DictReader(f, restkey='extra')
    for row in cf:
        print(row)

will print 将打印

{"Name": "Bob Smith", "Address": "123 main st", "Telephone": "111-111-1111"}
{"Name": "Jon Smith", "Address": "123 main st", "Telephone": "111-111-1111", "extra": ["222-222-2222"]}

You don't need DictReader . 您不需要DictReader Use the standard reader and tuple assignment syntax: 使用标准的reader和元组分配语法:

Code: 码:

import csv

with open('test.csv') as f:
    r = csv.reader(f)
    next(r) # skip header

    # Note this assigns the 3rd and remaining columns to 'telephone' as a list.
    for name,addr,*telephone in r:
        print(f'name:     {name}')
        print(f'address:  {addr}')
        for i,phone in enumerate(telephone,1):
            print(f'Phone #{i}: {phone}')
        print()

test.csv: test.csv:

Name,Address,Telephone
"Bob Smith","123 main st","111-111-1111"
"Jon Smith","123 main st","111-111-1111","222-222-2222"

Output: 输出:

name:     Bob Smith
address:  123 main st
Phone #1: 111-111-1111

name:     Jon Smith
address:  123 main st
Phone #1: 111-111-1111
Phone #2: 222-222-2222

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM