简体   繁体   中英

I can't figure out how to write to my data to a csv file as well as having my sorting code function correctly

if class_number == ('1') and sort_by == ('a') or ('A'):

    csv_file = open('Class1_Test_Score.csv', 'a')
    csv_file.write('\n')
    csv_file.write(sname + ' ' + fname)
    csv_file.write(',')
    csv_file.write(score)
    csv_file.close()

    sort1 = open('Class1_Test_Score.csv', 'r')
    sorting = csv.reader(sort1, delimiter = ',')
    sort = sorted(sorting,key=operator.itemgetter(1))

    for eachline in sort:
        csv_file.write(eachline)

Is every row in your Nested List its own list object with length greater than 0 ?

The majority of your rows are likely list objects with multiple items, giving it a :

    len ( row ) > 1 

But I'm guessing there may be at least one Row in your Nested List that has a length of 0. In other words whereas most of your rows look like this :

    [  'First Item' ,  2  ,  "3rd Item"   ]

There may be one Row that looks like this :

    [   ]

And you cannot sort with operator.itemgetter unless every row in that nested list has an item at index number 0 ( or another column number you choose to input in your itemgetter ).

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