Elisp: 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.

(rename-file "/home/joe/test1.txt" "/home/joe/test2.txt")

(copy-file "/home/joe/test1.txt" "/home/joe/test2.txt")

(delete-file "/home/joe/test2.txt")

Functions on Directory

(copy-directory "/home/joe/stuff" "/home/joe/stuff-backup")

;; delete a whole dir. new in emacs 23
(delete-directory "/home/joe/stuff" t)

(info "(elisp) Files")


(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."
  (let ((fName (buffer-file-name))
         backupName )
    (if (not fname)
        (error "current buffer is not a file." )
        (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.

;; get the dir path part
(file-name-directory "/home/joe/xyz.txt") ; "/home/joe/"

;; get filename part
(file-name-nondirectory "/home/joe/xyz.txt") ; "xyz.txt"

;; get filename's extension
(file-name-extension "/home/joe/cat.txt.jpg") ; "jpg"

;; get filename without extension
(file-name-sans-extension "/home/joe/cat.txt.jpg") ; "/home/joe/cat.txt"

;; get relative path
(file-relative-name "/home/joe/b/cat.jpg" "/home/joe/") ; "b/cat.jpg"

;; get full path
(expand-file-name "test.el")
;; sample output
;; "/home/joe/misc/emacs/test.el"

(info "(elisp) File Names")

Traverse Directory

Elisp: Walk Directory

Elisp Basic Functions

  1. Cursor
  2. Text Editing
  3. Get Buffer String
  4. String Functions
  5. Buffer
  6. Read/Write File
  7. File/Dir Path

If you have a question, put $5 at patreon and message me.
Or Buy Xah Emacs Tutorial
Or buy a nice keyboard: Best Keyboards for Emacs


Emacs Lisp