Check existence of directory and create if doesn't exist

check if file exists r
r create multiple directories
r delete directory
cannot create dir reason no such file or directory
create a sample csv file in the working directory
file.path r
create windows folder from r
how to create a directory in rstudio

I often find myself writing R scripts that generate a lot of output. I find it cleaner to put this output into it's own directory(s). What I've written below will check for the existence of a directory and move into it, or create the directory and then move into it. Is there a better way to approach this?

mainDir <- "c:/path/to/main/dir"
subDir <- "outputDirectory"

if (file.exists(subDir)){
    setwd(file.path(mainDir, subDir))
} else {
    dir.create(file.path(mainDir, subDir))
    setwd(file.path(mainDir, subDir))

}

Use showWarnings = FALSE:

dir.create(file.path(mainDir, subDir), showWarnings = FALSE)
setwd(file.path(mainDir, subDir))

dir.create() does not crash if the directory already exists, it just prints out a warning. So if you can live with seeing warnings, there is no problem with just doing this:

dir.create(file.path(mainDir, subDir))
setwd(file.path(mainDir, subDir))

How to check if a directory exists and how to create and create if , How to check in R whether a directory already exists and create it in case it does not - Reproducible example code - dir.create function explained. Check in R if a Directory Exists and Create if It doesn’t (Programming Example) Store Working Directory. Before we can start with the examples, it is helpful to store the working directory you want to Check for Existence of Sub-directory. In this section, we will try to create a new directory,

As of April 16, 2015, with the release of R 3.2.0 there's a new function called dir.exists(). To use this function and create the directory if it doesn't exist, you can use:

ifelse(!dir.exists(file.path(mainDir, subDir)), dir.create(file.path(mainDir, subDir)), FALSE)

This will return FALSE if the directory already exists or is uncreatable, and TRUE if it didn't exist but was succesfully created.

Note that to simply check if the directory exists you can use

dir.exists(file.path(mainDir, subDir))

R Check if Directory, Folder or File Exists and Create if It doesn't , To check the existence of a directory, you can use the following code: This code will return TRUE if a directory exists and FALSE otherwise. Check if a folder exists in a file path, if not, to create it under this specific file path, the following VBA code may help you to finish this job. 1. Hold down the ALT + F11 keys to open the Microsoft Visual Basic for Applications window. 2. Click Insert > Module, and paste the following code in the Module Window.

In terms of general architecture I would recommend the following structure with regard to directory creation. This will cover most potential issues and any other issues with directory creation will be detected by the dir.create call.

mainDir <- "~"
subDir <- "outputDirectory"

if (file.exists(paste(mainDir, subDir, "/", sep = "/", collapse = "/"))) {
    cat("subDir exists in mainDir and is a directory")
} else if (file.exists(paste(mainDir, subDir, sep = "/", collapse = "/"))) {
    cat("subDir exists in mainDir but is a file")
    # you will probably want to handle this separately
} else {
    cat("subDir does not exist in mainDir - creating")
    dir.create(file.path(mainDir, subDir))
}

if (file.exists(paste(mainDir, subDir, "/", sep = "/", collapse = "/"))) {
    # By this point, the directory either existed or has been successfully created
    setwd(file.path(mainDir, subDir))
} else {
    cat("subDir does not exist")
    # Handle this error as appropriate
}

Also be aware that if ~/foo doesn't exist then a call to dir.create('~/foo/bar') will fail unless you specify recursive = TRUE.

Check existence of directory and create if doesn't exist, well, I suppose you want to create if it doesn't exist, after checking so you could do it like that: or. 7~=exist(name,'dir') % check if folder does NOT exist  To check the existence of a directory, you can use the following code: This code will return TRUE if a directory exists and FALSE otherwise. dir.exists(file.path(mainDir, subDir)) This code will create a directory and if it exists already, it will return FALSE. dir.create(file.path(mainDir, subDir)) setwd(file.path(mainDir, subDir))

Here's the simple check, and creates the dir if doesn't exists:

## Provide the dir name(i.e sub dir) that you want to create under main dir:
output_dir <- file.path(main_dir, sub_dir)

if (!dir.exists(output_dir)){
dir.create(output_dir)
} else {
    print("Dir already exists!")
}

How to check if a directory(folder) exists?, Create a File; Check if File or Directory Exists; Create a Directory if it Does If it doesn't, you won't get an exception from the File constructor. To create a directory, first check if it already exists using os.path.exists(directory). Then you can create it using: import os if not os.path.exists('my_folder'): os.makedirs('my_folder') You can also use the python idiom EAFP: Easier to ask for forgiveness than permission. For example,

The use of file.exists() to test for the existence of the directory is a problem in the original post. If subDir included the name of an existing file (rather than just a path), file.exists() would return TRUE, but the call to setwd() would fail because you can't set the working directory to point at a file.

I would recommend the use of file_test(op="-d", subDir), which will return "TRUE" if subDir is an existing directory, but FALSE if subDir is an existing file or a non-existent file or directory. Similarly, checking for a file can be accomplished with op="-f".

Additionally, as described in another comment, the working directory is part of the R environment and should be controlled by the user, not a script. Scripts should, ideally, not change the R environment. To address this problem, I might use options() to store a globally available directory where I wanted all of my output.

So, consider the following solution, where someUniqueTag is just a programmer-defined prefix for the option name, which makes it unlikely that an option with the same name already exists. (For instance, if you were developing a package called "filer", you might use filer.mainDir and filer.subDir).

The following code would be used to set options that are available for use later in other scripts (thus avoiding the use of setwd() in a script), and to create the folder if necessary:

mainDir = "c:/path/to/main/dir"
subDir = "outputDirectory"

options(someUniqueTag.mainDir = mainDir)
options(someUniqueTag.subDir = "subDir")

if (!file_test("-d", file.path(mainDir, subDir)){
  if(file_test("-f", file.path(mainDir, subDir)) {
    stop("Path can't be created because a file with that name already exists.")
  } else {
    dir.create(file.path(mainDir, subDir))
  }
}

Then, in any subsequent script that needed to manipulate a file in subDir, you might use something like:

mainDir = getOption(someUniqueTag.mainDir)
subDir = getOption(someUniqueTag.subDir)
filename = "fileToBeCreated.txt"
file.create(file.path(mainDir, subDir, filename))

This solution leaves the working directory under the control of the user.

PHP: Create directory if it doesn't exist., To create a directory, first check if it already exists using os.path.exists(directory). Then you can create it using:import os if not  Or to check if a directory doesn't exist: if [ ! -d "$DIRECTORY" ]; then # Control will enter here if $DIRECTORY doesn't exist. fi However, as Jon Ericson points out, subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check.

Java File, Note that realpath() will return false if the file doesn't exist. have to enter to Services and configure Apache on "Open a session as" Create a new user I wrote this little handy function to check if an image exists in a directory, and if so, return  I'm building a small program using Access 2010 and am using the below to check for a folder and if it doesn't exist, then create it, which works: 'need code to create folder If Dir("C:\Michael\Test", vbDirectory) = "" Then MkDir ("C:\Michael\Test") Else 'do nothing for directory already exists End If

How can I create a directory if it does not exist using Python?, path.isdir(MYDIR) # If folder doesn't exist, then create it. if not CHECK_FOLDER: os.makedirs(  well, I suppose you want to create if it doesn't exist, after checking so you could do it like that:

file_exists - Manual, Here is a sample shell script to check if a directory doesn’t exist and create it as per our needs: #!/bin/bash dldir = " $HOME /linux/5.x" _out = "/tmp/out.$$" # Build urls url = "some_url/file.tar.gz" file = " ${url##*/} " ### Check for dir, if not found create it using the mkdir ## [ ! -d " $dldir " ] && mkdir -p " $dldir " # Now download it wget -qc " $url " -O " ${dldir} / ${file} " # Do something else below #

Comments
  • I'm sure I've seen an R function that creates a temporary directory with a randomly generated name and returns the name. I think there's a similar one that creates a temp file. I can't find them offhand, but the Databel package (cran.r-project.org/web/packages/DatABEL/index.html) has a function get_temporary_file_name.
  • You should never use setwd() in R code - it basically defeats the idea of using a working directory because you can no longer easily move your code between computers.
  • @hadley interesting topic to ponder, I'd appreciate your thoughts on other methods to the same end. At work, all computers are sync'd to the same network so file paths are consistent. If they aren't, we have bigger issues to deal with than portability of a script. In this particular example, I was writing a script that would be loaded on a machine that will be carried around our national parks for 2 years. This script will grab data from a local SQL instance, do some processing, and spit out a .csv. The end product will be a .bat file that the end user will never have to modify.
  • @Chase But you don't need to setwd to work with network paths. You just need to provide paths to save results and still work with current path (that one that is established when R session started). Or start R with desire working directory.
  • Yep. Or parametrize out_dir <- "path/to/output/directory" and then use write.table(file = file.path(out_dir,"table_1.csv"), ...). Or even out_file <- function(fnm) file.path("path/to/output/directory", fnm) and then write.table(file = out_file("table_1.csv"), ...) (similar method I use when working with network drives).
  • Be aware when using showWarnings = FALSE that this will also hide other warnings such as the directory being uncreateable.
  • ^ Is there a way to only suppress one specific warning?
  • Hi, I want ot create nested directory, like if I am in folder test1 then inside it test2 inside it test3 ... but right now I am facing problem. Is there a way that I can create 3 level of directory even if directory1 does not exits ??
  • @PraveenKesani Is this what you are looking for: dir.create("test1/test2/test3/", recursive=TRUE) ?
  • @Bas Really late response but suppressWarnings(<statement>) will suppress warnings for just that statement.