How to create directory if it doesn't exist?

Viewed 1723

If I want to write a file to C:/output/results.csv what's a simple way to make the directory if it doesn't exist? I want to do this because CSV.write(path,data) errors if C:/output/ doesn't exist.

mkdir errors if the directory already exists. I am currently doing the following, but is there a safer/cleaner way to do this?

try 
    mkdir("C:/output")
catch
    # if errors, likely already exists
end

Edit: As one of the commenters pointed out, mkpath will create a directory if it doesn't exist, and in either case will return the directory name.

My question was confounding the usage of mkdir (which errors if directory exists) and mkpath which does not error in that case.

2 Answers

You could explicitly check whether the directory exists beforehand using isdir:

isdir(dir) || mkdir(dir)
CSV.write(joinpath(dir, "results.csv"), data)

But this will not necessarily handle all corner cases, like when the path already exists but is a link to another directory. The mkpath function in the standard library should handle everything for you:

mkpath(path)
CSV.write(joinpath(path, "results.csv"), data)

mkpath(oath) will create a directory if it does not exist and return the path after doing so. If it already exists, the path is returned.

Related