Lean 4 (Meta)programming Cookbook

Deleting a file or Directory🔗

Contributors: Anirudh Gupta

How to delete a file🔗

You can delete a file using IO.FS.removeFile function. It returns an IO Unit which means it performs the action of deleting the file but does not return any value.

def deleteFile (path : String) : IO Unit := do try IO.FS.removeFile path IO.println s!"File {path} deleted successfully." catch e => IO.println s!"Failed to delete file {path}: {e}"

How to delete a directory🔗

You can delete a directory using IO.FS.removeDir function to delete an empty directory. If you want to delete all the contents inside the directory, use IO.FS.removeDirAll

def deleteEmptyDir (path : String) : IO Unit := do IO.FS.removeDir path def deleteDir (path: String) : IO Unit := do IO.FS.removeDirAll path

Refer to Creating directories section bottom to know more about why String works as a file path here.