help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: exporting nested list to CSV file


From: Christopher Howard
Subject: Re: exporting nested list to CSV file
Date: Tue, 22 Jul 2014 15:59:04 -0800

On Tue, 22 Jul 2014 14:25:17 -0800
Christopher Howard <address@hidden> wrote:

> 
> Thank you for helping me get started. I also needed to address the
> issues of 1) newlines at the end of rows and 2) character escaping. To
> address the second issue, I used "prin1", which I hope is a good
> enough hack for my purposes:
> 
> #+begin_src emacs-lisp
> (defun to-csv-row (fields)
>   (mapconcat 'prin1-to-string fields ","))
> 
> (defun to-csv-string (nested-list)
>   (mapconcat 'to-csv-row nested-list "\n"))
> 
> (defun to-csv-file (path nested-list)
>   "Converts NESTED-LIST to csv format and exports to file.
> NESTED-LIST is expected to be the structure provided by the pcsv
> library." (with-temp-file path
>     (insert (to-csv-string nested-list))))
> #+end_src

For posterity: CSV using repetition to escape quotes inside quotes:

#+begin_src emacs-lisp
(defun csv-quote-field (data)
  (mapconcat
   'identity
   `("\""
     ,(s-replace-all
       '(("\"" . "\"\"")) data)
     "\"") ""))

(defun to-csv-row (fields)
  (mapconcat 'csv-quote-field fields ","))

(defun to-csv-string (nested-list)
  (mapconcat 'to-csv-row nested-list "\n"))

(defun to-csv-file (path nested-list)
  "Converts NESTED-LIST to csv format and exports to file. NESTED-LIST is
   expected to be the structure provided by the pcsv library."
  (with-temp-file path
    (insert (to-csv-string nested-list))))
#+end_src



reply via email to

[Prev in Thread] Current Thread [Next in Thread]