Emacs Lisp: File and Directory Functions

By Xah Lee. Date: .

Here's the basic functions for file and directory.

{Rename, Copy, Delete} Files

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

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

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

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

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

File Name Manipulation

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

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

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

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

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

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

(info "(elisp) File Names")

Like it? Buy Xah Emacs Tutorial. Thanks.

or, buy something from Best Keyboard for Emacs