CSV Library

Behold! My simple CSV library. True, there is a CSV library built into Python (import csv) but mine does enough to make it more useful (in my humble opinion) and it's easy to understand.

import os

# Simple CSV handling library
# Written by Mr Mills
# Using this library
# ------------------
# a) Run or import this file or include the functions in your script
# b) Load a list from a CSV file
#    - execute 'sequence = csv2sequence(filename)' choosing a suitable filename
#    - returns 'False' if file does not exist
# c) Save a list to a CSV file
#    - create a list
#    - execute 'sequence2csv(list,filename)' choosing a suitable filename
# This file will ALWAYS overwrite a file if it already exists - be careful!

def csv2sequence(filename):
  """ Drag CSV file into a list """
  if os.path.isfile(filename):
    sequence = []
    handle = open(filename,'r')
    for line in handle:
      sequence.append(line.rstrip('\n').split(','))
    handle.close()
    return sequence
  else:
    print('File does not exist')
    return False

def sequence2csv(sequence,filename):
  """ Drop list into a CSV file """
  handle = open(filename,'w')
  for line in sequence:
    for i in range(len(line)):
      line[i] = str(line[i])
    handle.write(','.join(line)+'\n')
  handle.close()

Full instructions are included in the script and code hints will display by virtue of the triple quoted comments in the subroutines.  Just make sure that this file is in the same folder as the script that is using it (or a relative folder if you know how to access it).
ċ
csv.py
(1k)
Mark Mills,
18 Apr 2020, 13:34