programing

r을 사용한 폴더 관리 : 디렉터리가 있는지 확인하고 없으면 만듭니다.

sourcejob 2023. 7. 3. 22:48
반응형

r을 사용한 폴더 관리 : 디렉터리가 있는지 확인하고 없으면 만듭니다.

저는 종종 많은 출력을 생성하는 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))
    
}

사용하다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))

16일 , 4월 16일 와 .R 3.2.0라는새기있능습다니이운로▁▁new라는 새로운 기능이 dir.exists()이 경우 다음을.

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

반됩니다가 됩니다.FALSE수 없는 , 그리고 "Directory"는 "Create"입니다.TRUE존재하지 않지만 성공적으로 생성된 경우.

디렉토리가 존재하는지 간단히 확인하기 위해 사용할 수 있습니다.

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

다음은 간단한 검사이며 존재하지 않는 경우 디렉토리를 작성합니다.

## 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!")
}

한 줄:

if (!dir.exists(output_dir)) {dir.create(output_dir)}

예:

dateDIR <- as.character(Sys.Date())
outputDIR <- file.path(outD, dateDIR)
if (!dir.exists(outputDIR)) {dir.create(outputDIR)}

일반적인 아키텍처 측면에서 디렉토리 작성과 관련하여 다음과 같은 구조를 권장합니다.인 문제가 됩니다.dir.create콜.콜.

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
}

또한 다음과 같은 경우에도 주의해야 합니다.~/foo존재하지 않는 경우에 대한 호출입니다.dir.create('~/foo/bar')합니다.recursive = TRUE.

공유 네트워크 드라이브에서 트리 구조를 재귀적으로 만드는 동안 권한 오류가 발생하는 R 2.15.3 문제가 있었습니다.

이 이상함을 피하기 위해 수동으로 구조를 만듭니다.

mkdirs <- function(fp) {
    if(!file.exists(fp)) {
        mkdirs(dirname(fp))
        dir.create(fp)
    }
} 

mkdirs("H:/foo/bar")

디렉토리의 존재를 테스트하기 위해 file.exists()를 사용하는 것은 원래 게시물에서 문제가 됩니다.subDir에 단순히 경로가 아닌 기존 파일의 이름이 포함된 경우 file.exists()는 TRUE를 반환하지만 setwd() 호출은 작업 디렉터리를 파일을 가리키도록 설정할 수 없기 때문에 실패합니다.

file_test(op="-d", subDir)를 사용하는 것이 좋습니다. subDir이 기존 디렉토리이면 "TRUE"를 반환하지만 subDir이 기존 파일 또는 존재하지 않는 파일 또는 디렉토리이면 FALSE를 반환합니다.마찬가지로 op="-f"를 사용하여 파일을 확인할 수 있습니다.

또한 다른 설명에서 설명한 것처럼 작업 디렉터리는 R 환경의 일부이므로 스크립트가 아닌 사용자가 제어해야 합니다.스크립트는 R 환경을 변경하지 않는 것이 이상적입니다.이 문제를 해결하기 위해 옵션()을 사용하여 모든 출력을 원하는 전역에서 사용할 수 있는 디렉터리를 저장할 수 있습니다.

따라서 다음 솔루션을 고려해 보십시오. 일부 UniqueTag는 옵션 이름에 대한 프로그래머 정의 접두사일 뿐이므로 같은 이름의 옵션이 이미 존재할 가능성이 낮습니다. 예를 들어 "filer"라는 패키지를 개발하는 경우 filer.mainDir 및 filer.subDir을 사용할 수 있습니다.

다음 코드는 나중에 다른 스크립트에서 사용할 수 있는 옵션을 설정하고(따라서 스크립트에서 setwd()를 사용하지 않도록) 필요한 경우 폴더를 만드는 데 사용됩니다.

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

그런 다음 subDir에서 파일을 조작해야 하는 후속 스크립트에서 다음과 같은 방법을 사용할 수 있습니다.

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

이 솔루션은 작업 디렉토리를 사용자의 제어 하에 둡니다.

이 질문이 얼마 전에 한 질문이라는 것을 알지만, 유용한 경우에는,here패키지는 특정 파일 경로를 참조할 필요가 없고 코드를 더 쉽게 이동할 수 있도록 하는 데 매우 유용합니다.작업 디렉토리를 자동으로 정의합니다..Rproj파일이 위치하므로 작업 디렉터리에 대한 파일 경로를 정의할 필요 없이 다음과 같이 충분할 수 있습니다.

library(here)

if (!dir.exists(here(outputDir))) {dir.create(here(outputDir))}

경로가 올바른 디렉터리인지 확인하려면 다음을 시도하십시오.

file.info(cacheDir)[1,"isdir"]

file.info끝에 있는 슬래시는 신경 쓰지 않습니다.

file.exists디렉터리가 슬래시로 끝나면 디렉터리에 대해 실패하고 디렉터리 없이 성공합니다.따라서 경로가 디렉터리인지 확인하는 데 사용할 수 없습니다.

file.exists("R:/data/CCAM/CCAMC160b_echam5_A2-ct-uf.-5t05N.190to240E_level1000/cache/")
[1] FALSE

file.exists("R:/data/CCAM/CCAMC160b_echam5_A2-ct-uf.-5t05N.190to240E_level1000/cache")
[1] TRUE

file.info(cacheDir)["isdir"]

패키지hutils(내가 쓴) 기능이 있습니다.provide.dir(path)그리고.provide.file(path)디렉토리/파일을 확인하다path존재합니다. 존재하지 않는 경우 생성합니다.

언급URL : https://stackoverflow.com/questions/4216753/folder-management-with-r-check-existence-of-directory-and-create-it-if-it-does

반응형