Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from a file into a Emacs lisp list

Tags:

emacs

elisp

I have the following file data.txt

A
B
C
D

I would like to read the contents of this file into a Lisp list, like

(defun read-list-from-file (fn)
  (interactive)
  (list "A" "B" "C" "D"))

(defun my-read ()
  (interactive)
  (let (( mylist (read-list-from-file "data.txt")))
    (print mylist t)))

How can I modify read-list-from-file such that it returns the same list, but instead reads from the file given as input argument fn.. Each line in the file should be a separate item in the list..

like image 870
Håkon Hægland Avatar asked Dec 23 '13 16:12

Håkon Hægland


1 Answers

This code:

(with-current-buffer
    (find-file-noselect "~/data.txt")
  (split-string
   (save-restriction
     (widen)
     (buffer-substring-no-properties
      (point-min)
      (point-max)))
   "\n" t))

UPD:

Here's a version with insert-file-contents:

(defun slurp (f)
  (with-temp-buffer
    (insert-file-contents f)
    (buffer-substring-no-properties
       (point-min)
       (point-max))))

(split-string
 (slurp "~/data.txt") "\n" t)
like image 173
abo-abo Avatar answered Sep 20 '22 20:09

abo-abo