Emacs Lisp: File Path Functions

By Xah Lee. Date: . Last updated: .

File path string operations.

default-directory
A buffer local variable. Value is typically the dir path of the current buffer. You should not modify this variable.

Get File Path Parts

file-name-directory
return the dir part.
(file-name-directory "~/xyz.txt")
;; "~/"
file-name-nondirectory
return the file name part san dir.
(file-name-nondirectory "~/xyz.txt")
;; "xyz.txt"
file-name-extension
(file-name-extension FILENAME &optional PERIOD)

return the file name extension.

(file-name-extension "~/cat.jpg")
;; "jpg"
file-name-sans-extension
remove the file name extension.
(file-name-sans-extension "~/cat.tar.gz")
;; "~/cat.tar"
file-relative-name
(file-relative-name FILENAME &optional DIRECTORY)

return relative path, with respect to default-directory or DIRECTORY

(file-relative-name "~/b/cat.jpg" "~/")
;; "b/cat.jpg"
expand-file-name
(expand-file-name NAME &optional DEFAULT-DIRECTORY)

return the full path, from relative path.

(expand-file-name "test.el")
;; sample output
;; "c:/Users/xah/.emacs.d/temp/test.el"
directory-name-p
return true if it ends in a slash.
(directory-name-p "test.el")
file-name-as-directory
basically add a slash to the end, if none already. In emacs lisp, dir path must end in a slash.
(file-name-as-directory "~/.emacs.d/temp")
;; "~/.emacs.d/temp/"

Join File Paths

file-name-with-extension
(file-name-with-extension FILENAME EXTENSION)

join a file name with extension.

(file-name-with-extension "ff" "jpg")
;; "ff.jpg"

(file-name-with-extension "ff" ".jpg")
;; "ff.jpg"

file-name-concat
(file-name-concat DIRECTORY &rest COMPONENTS)

join file paths, and making sure there is one and only one slash between parts.

(file-name-concat "~/a")
;; "~/a"

(file-name-concat "~/a" "b")
;; "~/a/b"

(file-name-concat "~/a/" "b")
;; "~/a/b"

;; the second arg should not start with slash
(file-name-concat "~/a/" "/b")
;; "~/a//b"

(info "(elisp) File Names")

Emacs Lisp File/Buffer


Practical Elisp ⭐

Writing Command

Text Processing

Get User Input

File/Buffer

Writing Script