检查目录是否存在,如果不存在则创建 [英] Check existence of directory and create if doesn't exist
本文介绍了检查目录是否存在,如果不存在则创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我经常发现自己编写了生成大量输出的 R 脚本.我发现把这个输出放到它自己的目录中更干净.我在下面写的内容将检查目录是否存在并移入该目录,或者创建目录然后移入该目录.有没有更好的方法来解决这个问题?
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))
}
推荐答案
使用 showWarnings = FALSE
:
dir.create(file.path(mainDir, subDir), showWarnings = FALSE)
setwd(file.path(mainDir, subDir))
如果目录已经存在,
dir.create()
不会崩溃,它只是打印出警告.因此,如果您可以忍受看到警告,那么这样做就没有问题:
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))
这篇关于检查目录是否存在,如果不存在则创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文