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.

Elisp, Writing Scritpts

  1. Run Elisp Script in Shell
  2. Get Command Line Args
  3. Read File
  4. Read File Content as List
  5. Write File
  6. Print, Output
  7. Format String
  8. Walk Dir
  9. Call Shell Command
  10. Get Script Name at Run Time

If you have a question, put $5 at patreon and message me.
Or Buy Xah Emacs Tutorial
Or buy a nice keyboard: Best Keyboards for Emacs


Emacs Lisp