首页 > 解决方案 > 检查两个路径是否解析到同一个目录

问题描述

检查两个文件路径是否解析为同一个文件时,解决方案是使用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 包(v0.2.0) 于 2018 年 9 月 5 日创建。

在识别目录方面是否有可靠(或更可靠)的方法?

标签: rfilesystems

解决方案


如果您愿意为此使用一个包,那么我在fs包中获得了很大的成功,用于跨操作系统稳健的路径操作。例如,当它通过 规范化时fs::path_norm(),它将在 Windows 上去除这个尾部斜杠。

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

reprex 包(v0.2.0) 于 2018 年 9 月 5 日创建。


推荐阅读