检查目录是否存在,如果不存在则创建

我经常发现自己写的R脚本会产生大量输出。我发现将其输出放入其自己的目录更加干净。我在下面编写的内容将检查目录是否存在并移入该目录,或者创建目录然后移入该目录。有没有更好的方法来解决这个问题?


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))


}


函数式编程
浏览 660回答 3
3回答

慕标琳琳

用途showWarnings = FALSE:dir.create(file.path(mainDir, subDir), showWarnings = FALSE)setwd(file.path(mainDir, subDir))dir.create()如果该目录已经存在,则不会崩溃,它只会打印出警告。因此,如果您可以看到警告,那么这样做就没有问题:dir.create(file.path(mainDir, subDir))setwd(file.path(mainDir, subDir))

幕布斯6054654

自2015年4月16日起,随着的发布,R 3.2.0有一个名为的新功能dir.exists()。要使用此功能并创建目录(如果目录不存在),可以使用:ifelse(!dir.exists(file.path(mainDir, subDir)), dir.create(file.path(mainDir, subDir)), FALSE)FALSE如果目录已经存在或TRUE无法创建,并且目录不存在但创建成功,则将返回该目录。请注意,只需检查目录是否存在,即可使用dir.exists(file.path(mainDir, subDir))

RISEBY

就一般体系结构而言,我建议在目录创建方面采用以下结构。这将涵盖大多数潜在的问题,并且dir.create呼叫将检测到与目录创建有关的任何其他问题。mainDir <- "~"subDir <- "outputDirectory"if (file.exists(paste(mainDir, subDir, "/", sep = "/", collapse = "/"))) {&nbsp; &nbsp; cat("subDir exists in mainDir and is a directory")} else if (file.exists(paste(mainDir, subDir, sep = "/", collapse = "/"))) {&nbsp; &nbsp; cat("subDir exists in mainDir but is a file")&nbsp; &nbsp; # you will probably want to handle this separately} else {&nbsp; &nbsp; cat("subDir does not exist in mainDir - creating")&nbsp; &nbsp; dir.create(file.path(mainDir, subDir))}if (file.exists(paste(mainDir, subDir, "/", sep = "/", collapse = "/"))) {&nbsp; &nbsp; # By this point, the directory either existed or has been successfully created&nbsp; &nbsp; setwd(file.path(mainDir, subDir))} else {&nbsp; &nbsp; cat("subDir does not exist")&nbsp; &nbsp; # Handle this error as appropriate}另请注意,如果~/foo不存在,则dir.create('~/foo/bar')除非您指定,否则对的调用将失败recursive = TRUE。
打开App,查看更多内容
随时随地看视频慕课网APP