Elisp: File and Directory Functions

By Xah Lee. Date: . Last updated: .

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

Functions on File

rename-file

(rename-file FILE NEWNAME &optional OK-IF-ALREADY-EXISTS)

rename or move file

(rename-file "~/test1.txt" "~/test2.txt")
;; move file
;; second arg must be a dir, must end in slash
(rename-file "~/test1.txt" "~/.emacs.d/temp/")
copy-file

(copy-file FILE NEWNAME &optional OK-IF-ALREADY-EXISTS KEEP-TIME PRESERVE-UID-GID PRESERVE-PERMISSIONS)

copy file

(copy-file "~/test1.txt" "~/test2.txt")
;; copy file to a dir
;; second arg must be a dir, must end in slash
(copy-file "~/test1.txt" "~/.emacs.d/temp/")
delete-file
(delete-file "~/test2.txt")

Create Temp File

make-temp-file

(make-temp-file PREFIX &optional DIR-FLAG SUFFIX TEXT)

create temp file or dir with unique name at temporary-file-directory, and optionally with content.

temporary-file-directory

return the path of temp file dir of the operating system

Functions on Directory

directory-files

List files. 〔see Elisp: Walk Directory, List Files

make-directory

Create a directory.

delete-directory

Delete a whole dir.

new in Emacs 23 (date 2009-07)

(delete-directory "~/stuff" t)
copy-directory
(copy-directory "~/stuff" "~/stuff-backup")
directory-empty-p

new in Emacs 28 (date 2022)

other. unsorted

these are less used.

Reference

Elisp, File, Buffer