2 min read

Cleaning up the Downloads Folder

A task automation function in R

The Problem

Staying organized is a hard task! I often find myself trying new ways to organize emails, documents, or information. One folder on my computer that I often left untouched was my downloads folder. However, this weekend I decided to create a function in R that could quickly sort document types that I wanted to keep and remove document types that I didn’t want on my computer. For example, I often download research articles in a PDF format that sometimes are not immediately organized and remain in my downloads folder. They are then buried under reference files (e.g., PubMed, EndNote), Word documents, etc. until I can no longer find them quickly. Conversely, I’m not as interested in keeping file types such as zip or EndNote, but I don’t generally delete them from my downloads folder.

The Solution

I decided this weekend that I would write a function in R that would sort my downloads folder by file type and remove any file types that I didn’t want to keep. File types that I use and want to keep often (e.g., Word documents, images, PDF documents, etc.) can be placed in allowed_files within the function while all other file types will be removed. Additionally, the function has an argument called allowed_filetypes that can be used to add file types to the embedded allowed_files list. The function creates a folder for each document type and then transfers the documents to their respective folder. The function can be modified for your use by adding in or removing additional file types within the function or even changing the directory so that this can be applied to a different folder. The function as it is written below is on my GitHub page and can be installed via devtools::install_github(bhelsel/bhelselR).

The Function

sort_files_in_downloads <- function(allowed_filetypes = NULL){

  allowed_files <- c("docx", "pdf", "pptx", "html", "mov", "jpeg",
                     "jpg", "png", "xls", "xlsx", "doc", "csv")

  if(!is.null(allowed_filetypes)){
    allowed_files <- c(allowed_files, allowed_filetypes)
  }

  # Sort and clean the documents in my downloads folder
  files <- list.files("~/Downloads", full.names = TRUE)

  # Create folders from allowed file types
  ext <- unique(tools::file_ext(files))
  ext <- ext[ext %in% allowed_files]
  invisible(sapply(paste0("~/Downloads", "/", ext), function(x) if(!dir.exists(x)) dir.create(x)))

  # Prepare and move files from allowed file types
  files2move <- files[grepl("[.]", files) & tools::file_ext(files) %in% allowed_files]
  newpaths <- paste0(dirname(files2move), "/", tools::file_ext(files2move), "/", basename(files2move))
  invisible(file.copy(from = files2move, to = newpaths))
  invisible(file.remove(files2move))

  # Remove files that are not in allowed file types
  files2delete <- files[grepl("[.]", files) & !files %in% files2move]
  file.remove(files2delete)

}