Python code snippets

Reading a CSV of numbers to a list

import csv
with open(fileName, 'r') as read_obj:
	csv_reader = csv.reader(read_obj)
    list_of_csv = list(csv_reader)
# list_of_csv is a list[list[String]] where each list contains a row of the csv. 

Writing a list to a CSV

import csv
with open(fileName, 'w', newline='') as f:
  writer = csv.writer(f) # create the csv writer
  # write a row to the csv file
  write.writerow(fields)  # fileds is a list indicating column names or a string as a header
  writer.writerows(listOfRows) # each row is list/iterable List[List]
  # Or use writer.writerow(aRows) with a loop over a list/iterable of rows

Writing a File

 with open(filename, 'w') as f:
        for element in an_iterator:  # list, dict, etc...
        	f.write(rowString(element))  # rowString is a function or expression that 
          								 # makes string out of the content of element

Sorting a list of lists based on a specific index

z = [['a',2], ['v', 0.256]]
sorted(z, key = lambda item:  item[1])