从完整文件路径查找文件名


156

有没有一种方法可以从文件完整路径(文件路径的一部分)中提取文件名,而无需麻烦地处理字符串?

Java中的等效项为:

File f = new File ("C:/some_dir/a")
f.getName() //output a
f.getFullAbsolutePath() //output c:/some_dir/a

Answers:


286

basename("C:/some_dir/a.ext")
# [1] "a.ext"
dirname("C:/some_dir/a.ext")
# [1] "C:/some_dir"

21
我知道basename(),但是后来我忘记了。这些功能应在list.filesfile.path帮助页面的“另请参见”部分中提及
Paul Rougieux

6

tidyverse相当于生活在FS包。{fs}在后台使用libuv

library("fs")

path_file("/some/path/to/file.xyz")
#> [1] "file.xyz"

path_dir("/some/path/to/file.xyz")
#> [1] "/some/path/to"

reprex软件包(v0.3.0)创建于2020-02-19

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.