Skip to main content

delete-file

delete-file Function

Syntax:

delete-file filespec → t

Arguments and Values:

filespec—a pathname designator .

Description:

Deletes the file specified by filespec.

If the filespec designator is an open stream, then filespec and the file associated with it are affected (if the file system permits), in which case filespec might be closed immediately, and the deletion

might be immediate or delayed until filespec is explicitly closed, depending on the requirements of the file system.

It is implementation-dependent whether an attempt to delete a nonexistent file is considered to be successful.

delete-file returns true if it succeeds, or signals an error of type file-error if it does not.

The consequences are undefined if filespec has a wild component, or if filespec has a nil component and the file system does not permit a nil component.

Examples:

(with-open-file (s "delete-me.text" :direction :output :if-exists :error)) 
→ NIL
(setq p (probe-file "delete-me.text")) → #P"R:>fred>delete-me.text.1"
(delete-file p) → T
(probe-file "delete-me.text") → false
(with-open-file (s "delete-me.text" :direction :output :if-exists :error)
(delete-file s))
→ T
(probe-file "delete-me.text") → false

Exceptional Situations:

If the deletion operation is not successful, an error of type file-error is signaled.

An error of type file-error might be signaled if filespec is wild.

See Also:

pathname, logical-pathname, Section 20.1 (File System Concepts), Section 19.1.2 (Pathnames as Filenames)

Expanded Reference: delete-file

Deleting a file

delete-file removes a file from the file system and returns T on success.

(with-open-file (s "/tmp/cl-delete-test.txt" :direction :output
:if-exists :supersede)
(write-string "temporary data" s))

(probe-file "/tmp/cl-delete-test.txt")
=> #P"/tmp/cl-delete-test.txt"

(delete-file "/tmp/cl-delete-test.txt")
=> T

(probe-file "/tmp/cl-delete-test.txt")
=> NIL

Deleting via a pathname object

delete-file accepts any pathname designator: strings, pathnames, or streams.

(with-open-file (s "/tmp/cl-delete-test2.txt" :direction :output
:if-exists :supersede)
(write-string "temporary" s))

(delete-file #P"/tmp/cl-delete-test2.txt")
=> T

Error on nonexistent file

Whether deleting a nonexistent file signals an error is implementation-dependent. Many implementations signal a file-error.

;; This may signal a file-error on some implementations:
;; (delete-file "/tmp/no-such-file-xyz-99999.txt")
;; => signals FILE-ERROR (implementation-dependent)

Create-and-delete pattern

A common pattern is creating a temporary file, using it, then deleting it.

(let ((path "/tmp/cl-delete-temp.txt"))
(with-open-file (s path :direction :output :if-exists :supersede)
(write-string "work in progress" s))
;; ... use the file ...
(delete-file path)
(null (probe-file path)))
=> T