Read specific columns from a csv file with csv module?

后端 未结 12 1142
闹比i
闹比i 2020-11-22 10:06

I\'m trying to parse through a csv file and extract the data from only specific columns.

Example csv:

ID | N         


        
12条回答
  •  情书的邮戳
    2020-11-22 10:57

    import csv
    from collections import defaultdict
    
    columns = defaultdict(list) # each value in each column is appended to a list
    
    with open('file.txt') as f:
        reader = csv.DictReader(f) # read rows into a dictionary format
        for row in reader: # read a row as {column1: value1, column2: value2,...}
            for (k,v) in row.items(): # go over each column name and value 
                columns[k].append(v) # append the value into the appropriate list
                                     # based on column name k
    
    print(columns['name'])
    print(columns['phone'])
    print(columns['street'])
    

    With a file like

    name,phone,street
    Bob,0893,32 Silly
    James,000,400 McHilly
    Smithers,4442,23 Looped St.
    

    Will output

    >>> 
    ['Bob', 'James', 'Smithers']
    ['0893', '000', '4442']
    ['32 Silly', '400 McHilly', '23 Looped St.']
    

    Or alternatively if you want numerical indexing for the columns:

    with open('file.txt') as f:
        reader = csv.reader(f)
        reader.next()
        for row in reader:
            for (i,v) in enumerate(row):
                columns[i].append(v)
    print(columns[0])
    
    >>> 
    ['Bob', 'James', 'Smithers']
    

    To change the deliminator add delimiter=" " to the appropriate instantiation, i.e reader = csv.reader(f,delimiter=" ")

提交回复
热议问题