Package: fs


Function: file_delete()


1. Delete an observation file (“summary_obs.xlsx”) from a folder (“obs_2022-03-15”).

Let’s review the current files in both folders.

Files in “obs_2022-03-15”

base::basename(fs::dir_ls(here::here("file-system", "obs_2022-03-15")))
[1] "obs1.xlsx"        "obs2.xlsx"        "obs3.xlsx"        "summary_obs.xlsx"

Now let’s delete “summary_obs.xlsx”

fs::file_delete(path = here::here("file-system", "obs_2022-03-15", "summary_obs.xlsx"))

Now let’s view our files in the folder.

base::basename(fs::dir_ls(here::here("file-system", "obs_2022-03-15")))
[1] "obs1.xlsx" "obs2.xlsx" "obs3.xlsx"

2. Delete ALL files from a folder (“obs_2022-03-15”).

If we wanted to delete ALL files in the folder “obs_2022-03-15”, we could grab all our file names and pass that in our path.

files <- base::basename(fs::dir_ls(here::here("file-system", "obs_2022-03-15")))
    
fs::file_delete(path = here::here("file-system", "obs_2022-03-15", files))

Now let’s view our files in the folder.

They are all gone.

base::basename(fs::dir_ls(here::here("file-system", "obs_2022-03-15")))
character(0)

Another option is to delete the entire folder by simply not listing any specific files.

fs::file_delete(path = here::here("file-system", "obs_2022-03-15"))

Return to File System