Elisp: Read File Content as String or List of Lines

By Xah Lee. Date: . Last updated: .

Read File Content into a String

(defun get-string-from-file (filePath)
  "Return filePath's file content."
    (insert-file-contents filePath)
;; thanks to “Pascal J Bourguignon” and “TheFlyingDutchman [zzbba…@aol.com]”. 2010-09-02

Read File Content as List of Lines

(defun read-lines (filePath)
  "Return a list of lines of a file at filePath."
    (insert-file-contents filePath)
    (split-string (buffer-string) "\n" t)))

Once you have a list, you can use mapcar to process each element in the list. If you don't need the resulting list, use mapc.

Note: in elisp, it's more efficient to process text in a buffer than doing complicated string manipulation with string data type. But, if your lines are all short and you don't need to know the text that comes before or after current line, then, list of lines can be easier to work with.

If you have a question, put $5 at patreon and message me on xah discord.
Or support me by Buy Xah Emacs Tutorial

Emacs Tutorial

Emacs Init

Emacs Keys


ELisp Examples

ELisp Write Major Mode



Basic Functions

Writing Command

Writing Script

Lisp Data Structure

Lisp Symbol

Elisp Misc