Emacs Lisp: File and Directory Functions

By Xah Lee. Date: . Last updated: .

Here's the most useful functions for file and directory.

Functions on File

Basic functions on file and directory.

file-exists-p
rename-file
(rename-file "/home/joe/test1.txt" "/home/joe/test2.txt")
copy-file
(copy-file "/home/joe/test1.txt" "/home/joe/test2.txt")
delete-file
(delete-file "/home/joe/test2.txt")
set-file-modes

Functions on Directory

directory-files
make-directory
delete-directory
delete a whole dir. new in emacs 23.
(delete-directory "/home/joe/stuff" t)
copy-directory
(copy-directory "/home/joe/stuff" "/home/joe/stuff-backup")

(info "(elisp) Files")

Example:

(defun make-backup ()
  "Make a backup copy of current buffer's file.
Create a backup of current buffer's file.
The new file name is the old file name with trailing “~”, in the same dir.
If such a file already exist, append more “~”.
If the current buffer is not associated with a file, its a error."
  (interactive)
  (let ((fName (buffer-file-name))
         backupName )
    (if (not fname)
        (error "current buffer is not a file." )
      (progn
        (setq backupName (concat fName "~"))
        (while (file-exists-p backupName)
          (setq backupName (concat backupName "~")))
        (copy-file fName backupName t)
        (message (concat "Backup saved as: " (file-name-nondirectory backupName)))))))

File Path Functions

Basic functions on file path.

file-name-directory
(file-name-directory "/home/joe/xyz.txt")
;; "/home/joe/"
file-name-nondirectory
(file-name-nondirectory "/home/joe/xyz.txt")
;; "xyz.txt"
file-name-extension
(file-name-extension "/home/joe/cat.jpg")
;; "jpg"
file-name-sans-extension
(file-name-sans-extension "/home/joe/cat.tar.gz")
;; "/home/joe/cat.tar"
file-relative-name
(file-relative-name "/home/joe/b/cat.jpg" "/home/joe/")
;; "b/cat.jpg"
expand-file-name
(expand-file-name "test.el")
;; sample output
;; "/home/joe/misc/emacs/test.el"
default-directory
Variable. The current dir.

(info "(elisp) File Names")

Traverse Directory

Emacs Lisp: Walk Directory, List File Names

ErgoEmacs mascot-s276x226
Buy Xah Emacs Tutorial

Practical Elisp ⭐

Writing Command

Writing Script