Python 我能';我不知道如何将我的数据写入csv文件,以及如何正确使用排序代码

Python 我能';我不知道如何将我的数据写入csv文件,以及如何正确使用排序代码,python,csv,Python,Csv,嵌套列表中的每一行是否都有自己的长度大于0的列表对象 您的大多数行可能都是包含多个项的列表对象,这给了它一个: 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(','

嵌套列表中的每一行是否都有自己的长度大于0的列表对象

您的大多数行可能都是包含多个项的列表对象,这给了它一个:

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)
但我猜嵌套列表中可能至少有一行的长度为0。换句话说,您的大多数行都是这样的:

    len ( row ) > 1 
可能有一行如下所示:

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

并且不能使用operator.itemgetter进行排序,除非嵌套列表中的每一行都有一个索引号为0的项(或您选择在itemgetter中输入的另一个列号)

在尝试写入之前,您正在关闭文件。我已将代码更改为:if class_number==('1')和sort_by==('a')或('a'):csv_file=open('Class1_Test_Score.csv','a')csv_文件。write('\n')csv_文件。write(sname+''+fname)csv_文件。write(','))csv_文件。write(Score)sort1=open('Class1_Test_Score.csv','r')sorting=csv.reader(sort1,delimiter=',')sort=sorted(排序,key=operator.itemgetter(0)),用于排序:csv_file.write(eachline)csv_file.close(),但我仍然收到以下错误消息:sort=sorted(排序,key=operator.itemgetter(0))索引器:列表索引超出范围
    [   ]