Function: file-name-with-extension
file-name-with-extension is a byte-compiled function defined in
files.el.gz.
Signature
(file-name-with-extension FILENAME EXTENSION)
Documentation
Return FILENAME modified to have the specified EXTENSION.
The extension (in a file name) is the part that begins with the last ".". This function removes any existing extension from FILENAME, and then appends EXTENSION to it.
EXTENSION may include the leading dot; if it doesn't, this function will provide it.
It is an error if FILENAME or EXTENSION is empty, or if FILENAME
is in the form of a directory name according to directory-name-p.
See also file-name-sans-extension.
Other relevant functions are documented in the file-name group.
Probably introduced at or before Emacs version 28.1.
Shortdoc
;; file-name
(file-name-with-extension "foo.txt" "bin")
=> "foo.bin"
(file-name-with-extension "foo" "bin")
=> "foo.bin"
Source Code
;; Defined in /usr/src/emacs/lisp/files.el.gz
(defun file-name-with-extension (filename extension)
"Return FILENAME modified to have the specified EXTENSION.
The extension (in a file name) is the part that begins with the last \".\".
This function removes any existing extension from FILENAME, and then
appends EXTENSION to it.
EXTENSION may include the leading dot; if it doesn't, this function
will provide it.
It is an error if FILENAME or EXTENSION is empty, or if FILENAME
is in the form of a directory name according to `directory-name-p'.
See also `file-name-sans-extension'."
(let ((extn (string-trim-left extension "[.]")))
(cond ((string-empty-p filename)
(error "Empty filename"))
((string-empty-p extn)
(error "Malformed extension: %s" extension))
((directory-name-p filename)
(error "Filename is a directory: %s" filename))
(t
(concat (file-name-sans-extension filename) "." extn)))))