Package: list2csv
List2CSVList2CSV is a simple package that helps with writing lists of objects to CSV
files.Installationlist2csv can be downloaded frompypior
installed using pip:pip install list2csvUsageList2CSV exposes aWriterclass that manages CSV columns and writing to a
TextIO stream. Columns are first configured on aWriterinstance before data
is written in CSV format to the stream.The following examples will use thisStudentclass and list to demonstrate
usage.fromdataclassesimportdataclassfromstatisticsimportmean@dataclassclassStudent:student_id:strtest_1_mark:floattest_2_mark:floatassignment_marks:list[float]lab_marks:list[float]comments:list[str]@propertydefgrade(self):return(60*mean((self.test_1_mark,self.test_2_mark))+30*mean(self.assignment_marks)+10*mean(self.lab_marks))/100students=[Student('abcd123',78.5,88,[84.5,96,87],[92.3,98,100,70],['Good','Needs work on classes']),Student('efgh456',62,74,[70.5,76,80],[98,68.2,0,93.5],['Good','Needs work on formatting','Needs work on recursion']),Student('ijkl789',100,99.5,[98.5,100,100],[100,100,98.7,100],['Excellent']),]Adding ColumnsThe most basic column configuration is to use theadd_columnmethod to add a
column with a name and a function that returns the value for that column.Column data can be formatted with an optional format string to specify how data
should be formatted as it is written to the CSV file.importlist2csvwithopen('grades.csv')asf:writer=list2csv.Writer(f)writer.add_column('ID',lambdas:s.student_id)writer.write_header()writer.write_all(students)Which will produce the following table:IDabcd123efgh456ijkl789However, instead of a function,lambda s: s.student_id, you can also use a
string of the attribute name of the objects being written:importlist2csvwithopen('grades.csv','w',newline='')asf:writer=list2csv.Writer(f)writer.add_column('ID','student_id')writer.write_header()writer.write_all(students)Would produce the same table as before.Several columns can be added with subsequent calls toadd_column.importlist2csvwithopen('grades.csv','w',newline='')asf:writer=list2csv.Writer(f)writer.add_column('ID','student_id')writer.add_column('Test 1','test_1_mark','{:.2f}')writer.add_column('Test 2','test_2_mark','{:.2f}')writer.write_header()writer.write_all(students)Would produce the following table:IDTest 1Test 2abcd12378.588efgh4566274ijkl78910099.5CountersCounter columns can be added which increment by a given step value for each row
written to the CSV. Counter columns have a default start value of 1 and a
default step value of 1.withopen('grades.csv','w',newline='')asf:writer=list2csv.Writer(f)writer.add_counter('Student Num')writer.add_column('ID','student_id')writer.add_column('Test 1','test_1_mark','{:.2f}')writer.add_column('Test 2','test_2_mark','{:.2f}')writer.write_header()writer.write_all(students)Which would produce the following table:Student NumIDTest 1Test 21abcd12378.5882efgh45662743ijkl78910099.5Any number of counters with separate start and step values can be added to the
same CSV file.Multi ColumnsIt is often desirable to write iterables of data to separate columns of a CSV
file. in such cases, a multi_column can be added to theWriterinstance.Multi columns take aheadder_formatteras opposed to aheadername. Each
resulting column will be namedheader_template.format(i), whereiis the
one-based index of the column.Multi columns will also need to be defined with the number of columns that will
be added.withopen('grades.csv','w',newline='')asf:writer=list2csv.Writer(f)writer.add_counter('Student Num')writer.add_column('ID','student_id')writer.add_column('Test 1','test_1_mark','{:.2f}')writer.add_column('Test 2','test_2_mark','{:.2f}')writer.add_multi('Assignment{}','assignment_marks',3,'{:.2f}')writer.write_header()writer.write_all(students)Would produce the following table:Student NumIDTest 1Test 2Assignment 1Assignment 2Assignment 31abcd12378.5088.0084.5096.0087.002efgh45662.0074.0070.5076.0080.003ijkl789100.0099.5098.50100.00100.00Aggregator ColumnsAggregator columns can collate the data from several columns into a single
column. Each column can be added with a set of aggregator IDs. When aggregator
columns are added with an ID, all columns with a matching ID will be aggregated
into a single column using an aggregator function. For example:withopen('grades.csv','w',newline='')asf:writer=list2csv.Writer(f)writer.add_counter('Student Num')writer.add_column('ID','student_id')writer.add_column('Test 1','test_1_mark','{:.2f}',{'test'})writer.add_column('Test 2','test_2_mark','{:.2f}',{'test'})writer.add_aggregator('test','Av Test Mark',mean,'{:.2f}')writer.add_multi('Assignment{}','assignment_marks',3,'{:.2f}',{'assignment'})writer.add_aggregator('assignment','Av Assignment Mark',mean,'{:.2f}')writer.write_header()writer.write_all(students)Would produce the following table:Student NumIDTest 1Test 2Av Test MarkAssignment 1Assignment 2Assignment 3Av Assignment Mark1abcd12378.5088.0083.2584.5096.0087.0089.172efgh45662.0074.0068.0070.5076.0080.0075.503ijkl789100.0099.5099.7598.50100.00100.0099.50While aggregator columns may be useful for aggregating data from multiple
attributes, in the case of aggregating multi columns it may just be more useful
to add a single column with an aggregating function. For example:...writer.add_multi('Assignment{}','assignment_marks',3,'{:.2f}')writer.add_column('Av Assignment Mark',lambdas:mean(s.assignment_marks),'{:.2f}')...Extended Examplewithopen('grades.csv','w',newline='')asf:writer=list2csv.Writer(f)writer.add_counter('Student Num')writer.add_column('ID','student_id')writer.add_column('Test 1','test_1_mark','{:.2f}',{'test'})writer.add_column('Test 2','test_2_mark','{:.2f}',{'test'})writer.add_aggregator('test','Av Test Mark',mean,'{:.2f}')writer.add_multi('Assignment{}','assignment_marks',3,'{:.2f}',{'assignment'})writer.add_aggregator('assignment','Av Assignment Mark',mean,'{:.2f}')writer.add_multi('Lab{}','lab_marks',4,'{:.2f}',{'lab'})writer.add_aggregator('lab','Av. Lab Mark',mean,'{:.2f}')writer.add_column('Grade','grade','{:.2f}')writer.add_column('Comments',lambdas:'\n'.join(s.comments))writer.write_header()writer.write_all(students)Student NumIDTest 1Test 2Av Test MarkAssignment 1Assignment 2Assignment 3Av Assignment MarkLab 1Lab 2Lab 3Lab 4Av. Lab MarkGradeComments1abcd12378.5088.0083.2584.5096.0087.0089.1792.3098.00100.0070.0090.0885.71GoodNeeds work on classes2efgh45662.0074.0068.0070.5076.0080.0075.5098.0068.200.0093.5064.9269.94GoodNeeds work on formattingNeeds work on recursion3ijkl789100.0099.5099.7598.50100.00100.0099.50100.00100.0098.70100.0099.6799.67ExcellentNoteFiles should be opened withnewline=''to allow for universal newline support.