Elisp: Read File

By Xah Lee. Date: . Last updated: .

Open File for Reading in Batch Script

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
    ))

To write to file, us write-region in the body. See Elisp: Write File

(info "(elisp) Current Buffer")

Read File as String or List of Lines

Elisp: Read File Content as String or List of Lines

find-file

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")

Note that find-file is very slow, because it has lots side-effects. 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 that slows down emacs.

find-file-hook is a variable defined in 'files.el'.
Its value is

(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)

Original value was nil

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)

Practical Emacs Lisp

Basics

Basic Functions

Writing Command

Writing Script