代码之家  ›  专栏  ›  技术社区  ›  Hugh

检查两个路径是否解析到同一目录

  •  2
  • Hugh  · 技术社区  · 8 年前

    Check if two file paths resolve to the same file normalizePath ;但是,这对于目录似乎不是决定性的:

    td1 <- tempdir()
    td2 <- paste0(td1, "/")
    
    dir.exists(td1) && dir.exists(td2)
    #> [1] TRUE
    file.create(file.path(td1, "foo.txt"))
    #> [1] TRUE
    file.exists(file.path(td2, "foo.txt"))
    #> [1] TRUE
    
    normalizePath(td1) == normalizePath(td2)
    #> [1] FALSE
    
    sessionInfo()
    #> R version 3.5.1 (2018-07-02)
    #> Platform: x86_64-w64-mingw32/x64 (64-bit)
    #> Running under: Windows 10 x64 (build 17134)
    #> 
    #> Matrix products: default
    #> 
    #> locale:
    #> [1] LC_COLLATE=English_Australia.1252  LC_CTYPE=English_Australia.1252   
    #> [3] LC_MONETARY=English_Australia.1252 LC_NUMERIC=C                      
    #> [5] LC_TIME=English_Australia.1252    
    #> 
    #> attached base packages:
    #> [1] stats     graphics  grDevices utils     datasets  methods   base     
    #> 
    #> loaded via a namespace (and not attached):
    #>  [1] compiler_3.5.1  backports_1.1.2 magrittr_1.5    rprojroot_1.3-2
    #>  [5] tools_3.5.1     htmltools_0.3.6 yaml_2.2.0      Rcpp_0.12.18   
    #>  [9] stringi_1.1.7   rmarkdown_1.10  knitr_1.20      stringr_1.3.1  
    #> [13] digest_0.6.16   evaluate_0.11
    

    reprex package (第0.2.0版)。

    1 回复  |  直到 8 年前
        1
  •  1
  •   jennybryan    8 年前

    如果你愿意为此使用一个包,我在 fs 用于跨操作系统健壮的路径操作的包。当它通过 fs::path_norm() ,例如,它将在窗口上删除此尾部斜杠。

    td1 <- tempdir()
    td2 <- paste0(td1, "/")
    
    dir.exists(td1) && dir.exists(td2)
    #> [1] TRUE
    file.create(file.path(td1, "foo.txt"))
    #> [1] TRUE
    file.exists(file.path(td2, "foo.txt"))
    #> [1] TRUE
    
    normalizePath(td1) == normalizePath(td2)
    #> [1] FALSE
    
    library(fs)
    path_norm(td1) == path_norm(td2)
    #> [1] TRUE
    
    sessionInfo()
    #> R version 3.4.3 (2017-11-30)
    #> Platform: x86_64-w64-mingw32/x64 (64-bit)
    #> Running under: Windows 10 x64 (build 17134)
    #> 
    #> Matrix products: default
    #> 
    #> locale:
    #> [1] LC_COLLATE=English_United States.1252 
    #> [2] LC_CTYPE=English_United States.1252   
    #> [3] LC_MONETARY=English_United States.1252
    #> [4] LC_NUMERIC=C                          
    #> [5] LC_TIME=English_United States.1252    
    #> 
    #> attached base packages:
    #> [1] stats     graphics  grDevices utils     datasets  methods   base     
    #> 
    #> loaded via a namespace (and not attached):
    #>  [1] compiler_3.4.3  backports_1.1.2 magrittr_1.5    rprojroot_1.3-2
    #>  [5] tools_3.4.3     htmltools_0.3.6 yaml_2.1.16     Rcpp_0.12.18   
    #>  [9] stringi_1.1.6   rmarkdown_1.8   knitr_1.17      stringr_1.2.0  
    #> [13] digest_0.6.16   evaluate_0.10.1
    

    创建日期:2018-09-05 reprex package (第0.2.0版)。