Elisp: Write File

By Xah Lee. Date: . Last updated: .

Write Region to File

To write to a file in a batch script, most of the time you want write-region

;; write current buffer's content to ~/temp.el
(write-region (point-min) (point-max) "~/temp.el")

Note: in batch script you should not use write-file. “write-file” is like other editor's “Save As”. It has side-effects such as opening the file, run its major mode and hooks, and is slow. [see Emacs Lisp Text Processing: find-file vs with-temp-buffer]

Write String to File

(write-region "something something" nil "filepath")

Open, Read, Possibly Write

If you want to write to file ONLY when you actually changed the file, you can create flag variable and use write-region, like this:

(defun my-process-file (fPath)
  "Process the file at path FPATH …"
  (let ((fileChanged-p nil))
    (with-temp-buffer
      (insert-file-contents fPath)

      ;; process text
      ;; set fileChanged-p to t or nil

      (when fileChanged-p (write-region (point-min) (point-max) fPath)))))

Create New File

If you want to create new file, use with-temp-file.

(with-temp-file path &rest body)

it'll create a new buffer, then run body, then it'll write to file at path. Existing file at path are overwritten.

;; create new buffer, do things, then write to file at fpath
(with-temp-file fpath
  (insert-file-contents fpath)

  ;; insert text here

  )

Append to File

(append-to-file START END FILENAME)

;; append whole buffer content to a file
(append-to-file (point-min) (point-max) "filePath")

(info "(elisp) Writing to Files")

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

ELisp Examples

ELisp Write Major Mode


ELisp

Basics

Basic Functions

Writing Command

Writing Script

Lisp Data Structure

Lisp Symbol

Elisp Misc