Elisp: Read File
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 the 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:
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
Elisp, File, Buffer
- Elisp: Buffer Functions
- Elisp: Read File
- Elisp: Read File Content as String or Lines
- Elisp: Write File
- Elisp: Open File, Read, Possibly Write
- Elisp: File and Directory Functions
- Elisp: Get File Info
- Elisp: File Path Functions
- Elisp: Walk Directory, List Files
- Elisp: Walk Directory by Depth 🚀
- Elisp: Get Dired Marked Files