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))
      (insert-file-contents fPath)

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

      (when fileChanged-p (write-region 1 (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")

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
Patreon me $5 patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs

If you have a question, put $5 at patreon and message me.