reading a CSV files columns directly into variables names with python

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

    I recognize this post is almost two years old, but I want to begin contributing positively to stackoverflow.

    I assume you want this to be more general than just three columns, but that efficiency doesn't matter.

    import csv
    f = csv.reader(open('my file.csv','r'))
    e = f.next() #Give us a sample of our data
    ecount = len(e)
    for i in range(ecount): #use range here to keep variable order in CSV preserved in naming
        vars()['ColumnName'+str(i+1)]] = list(e[i]) # makes a list for each item 
    for j in f:
        for l in range(ecount): 
            vars()['ColumnName'+str(l+1)].append(j[l]) #Reads in variable values to list
    

提交回复
热议问题