简体   繁体   中英

Converting csv columns to rows with python

I'm trying to create a list that will take data from gradebook.csv and change it to a different format.

gradebook.csv has columns like with data:

{ studentID , assignment1 , assignment2 , . . . assignmentN }
{ 2343      ,             ,   34.2      ,                   }

empty cells are assignments with no submission. Cells with numbers represent grades. This data will go into a list of the format:

{ studentID , assignmentid , grade }
{ 2343      , assignment2  , 34.2  }

the end result will be putting this data into a sql table in sql server 2012. The code below does what I want, but only for the last row in gradebook.csv . What am I doing wrong?

import csv

with open('gradebook.csv','rb') as g:
        gr=csv.reader(g)
        for row in gr:
            if row[0]=='User ID':
                pass
            else:
                studentid=row[0]
                individualassignments=[]
                everyone=[]
                for element in row[1:]:
                    if element=='':
                        pass
                    else:
                        individualassignments.append(element)

                individualassignments.append(studentid)
                everyone.append(individualassignments)

It looks like you clear out the everyone list (by setting everyone=[] ) for each iteration of your outer for loop. So only your last row in the csv file will be in the list.

To fix, you need to declare everyone outside of the loop

import csv

with open('gradebook.csv','rb') as g:
    gr=csv.reader(g)
    everyone=[]  # declare everyone here
    for row in gr:
        if row[0]=='User ID':
            pass
        else:
            studentid=row[0]
            individualassignments=[]               
            for element in row[1:]:
                if element=='':
                    pass
                else:
                    individualassignments.append(element)

            individualassignments.append(studentid)
            everyone.append(individualassignments)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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