reading a CSV files columns directly into variables names with python

前端 未结 6 2043
梦毁少年i
梦毁少年i 2021-02-06 12:57

I want to read a CSV file\'s columns directly into variables. The result should be something like you would get with the following shell line: while IFS=, read ColumnName1

6条回答
  •  名媛妹妹
    2021-02-06 13:30

    Here's a "dictreader" for a headless csv, each row will be a dictionary with sequential keys 'column_0', 'column_1', 'column_2' and so on...

    import csv
    
    csvfile = list(csv.reader(open('data.csv')))
    
    csvdics = []
    
    for row in csvfile:
        row_dict = {}
        for i in xrange(len(row)):
            row_dict['column_%s' % i] = row[i]
        csvdics.append(row_dict)
    

    Or, if you know ahead of time what the column names should be, you can pass them in a list as a second argument to DictReader.

提交回复
热议问题