ELisp: Read File

By Xah Lee. Date: . Last updated: .

Open File for Read Only

To process thousands of files, read only, use with-temp-buffer.

(defun my-process-file (fPath)
  "Process the file at path FPATH"
  (with-temp-buffer
    (insert-file-contents fPath)
    ;; do something
    ))

Read File as String or List of Lines

Open File, Visible to User, with Syntax Coloring, Etc

find-file
(find-file FILENAME &optional WILDCARDS)

Creates a new buffer, associate it with FILENAME, switch to the buffer. Return a buffer object.

FILENAME can be a full path or just a file name. This can be used to create a new file, when FILENAME does not exist. When the buffer is saved, the file will be created.

(find-file "~/test.txt")

WARNING: find-file is a user-oriented command. It is very slow, because it has lots side-effects. For example:

  • Loads a major mode (which does syntax coloring, usually very slow),
  • Record undo for any modification in the buffer.
  • Calls functions in find-file-hook.

Here's example of functions that are added to find-file-hook:

  • global-xah-math-input-mode-check-buffers
  • url-handlers-set-buffer-mode
  • global-display-line-numbers-mode-check-buffers
  • auto-revert--global-adopt-current-buffer
  • auto-revert-find-file-function
  • recentf-track-opened-file
  • epa-file-find-file-hook
  • global-eldoc-mode-check-buffers
  • global-font-lock-mode-check-buffers
  • vc-refresh-state
  • save-place-find-file-hook

if you really want to open the file as buffer in your batch script, then the following is helpful to speed it up:

(global-font-lock-mode 0)
(setq find-file-hook nil)
(setq buffer-undo-list t)

[see Emacs Lisp Text Processing: find-file vs with-temp-buffer]

Close File

kill-buffer
(kill-buffer &optional BUFFER-OR-NAME)
Close current buffer or a specified buffer.
;; close a buffer
(kill-buffer myBuffName)

Reference

Emacs Lisp, File, Buffer