simple-csv. A library to read/  write CSV files.
1 Reading CSV Files

simple-csv. A library to read/write CSV files.

Pragun Maharaj Goyal <[email protected]>

simple-csv is a small, simple csv reading/writing library for Racket.

1 Reading CSV Files

The following code snippet shows how simple-csv can be used to create a row-generator object, which returns the next row of the CSV file as a list. The internal mechanics of the csv-reader uses the read-char function on the string port. So, if you have a huge csv file, the csv-reader does not load all of it into memory.

(require simple-csv)
(define file-path "/home/username/some-csv-file.csv")
(define f (open-input-file file-path #:mode 'text))
(define row-generator ((make-csv-reader) f))

Changing CSV dialects CSV is a loosely defined standard (RFC 4180, so the CSV Reader can be tweaked for different dialects of CSV as follows.

(define csv-reader (make-csv-reader
                    #:delimiter #\,
                    #:lineterminator #\newline
                    #:escapechar #\\
                    #:doublequote #t
                    #:quotechar #\"
                    #:quoting #t
                    #:skipinitialspace #t))
(define row-generator (csv-reader f))

Reading the whole file into a list If you need the whole file read into a list in a single go. The following code snippet might help.
(define csv-list (for/list ([row (in-producer row-generator)]
                            #:break (eof-object? row))
Alternatively, you could also call row-gen->list, which does exactly what the code snippet above shows.

(define csv-list (row-gen->list row-generator))

End of File The row-generator returns a eof-object when it reaches the end of the file. This condition can be checked with a eof-object?.