reading a CSV files columns directly into variables names with python

前端 未结 6 2134
梦毁少年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:42

    Is this what you were looking for (Python 3.X):

    import csv
    from io import StringIO
    
    # Simulate a csv data file with no header
    data = StringIO('''\
    Mark,44,1
    Joe,22,0
    Craig,39,3
    ''')
    
    for row in csv.DictReader(data,'Name Age Children'.split()):
        print(row)
    

    Output

    {'Age': '44', 'Name': 'Mark', 'Children': '1'}
    {'Age': '22', 'Name': 'Joe', 'Children': '0'}
    {'Age': '39', 'Name': 'Craig', 'Children': '3'}
    

    Or maybe:

    import csv
    from io import StringIO
    
    # Simulate a csv data file with no header
    data = StringIO('''\
    Mark,44,1
    Joe,22,0
    Craig,39,3
    ''')
    
    # 1. Read in all the data
    # 2. Transpose into columns
    # 3. Match with column names
    # 4. Create dictionary
    cols = dict(zip('Name Age Children'.split(),zip(*csv.reader(data))))
    print(cols)
    

    Output

    {'Age': ('44', '22', '39'), 'Name': ('Mark', 'Joe', 'Craig'), 'Children': ('1', '0', '3')}
    

提交回复
热议问题