200

Is there a way to extract the file name from the file full path (part of a file path) without the hassle of manipulating string?

The equivalent in Java would be:

File f = new File ("C:/some_dir/a")
f.getName() //output a
f.getFullAbsolutePath() //output c:/some_dir/a
zx8754
  • 52,746
  • 12
  • 114
  • 209
defoo
  • 5,159
  • 11
  • 34
  • 39

4 Answers4

376

Use

basename("C:/some_dir/a.ext")
# [1] "a.ext"
dirname("C:/some_dir/a.ext")
# [1] "C:/some_dir"
MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
mjv
  • 73,152
  • 14
  • 113
  • 156
  • 28
    I knew about `basename()`, but then I forgot. These functions should be mentioned in the "See also" section of the [list.files](https://stat.ethz.ch/R-manual/R-devel/library/base/html/list.files.html) and [file.path](https://stat.ethz.ch/R-manual/R-devel/library/base/html/file.path.html) help pages. – Paul Rougieux Mar 30 '16 at 16:42
  • 4
    Yes. I search google and stumble upon this answer about once a week. – mzuba Sep 08 '20 at 12:47
  • 1
    how about extracting the basename without the extension? is that a native function as well? – Honeybear Nov 10 '20 at 23:35
  • 2
    @PaulRougieux I submitted a feature request, and this should be included in an upcoming R release :) – Gregor Thomas Feb 08 '21 at 14:19
24

The tidyverse equivalent lives in the fs package. {fs} makes use of libuv under the hood.

library("fs")

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

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

Created on 2020-02-19 by the reprex package (v0.3.0)

pat-s
  • 5,992
  • 1
  • 32
  • 60
  • Very helpful, thank you. Just used this code to set names for a list column, which was incredibly tedious without path_file() – James Crumpler Feb 23 '21 at 16:31
2

@Honeybear. The function that removes the extension from the filename you could use is the function from the {tools} R package

tools::file_path_sans_ext("ABCD.csv")
## [1] "ABCD"

See this post in SO

Maddocent
  • 53
  • 6
1

While trying to find the fastest method to extract a filename from a path in R I found that using sub with the regex ".*/" was ~an order of magnitude faster than basename (if speed is an issue).

files<-paste0("http://some/ppath/to/som/cool/file/",1:1000,".flac")

sub(".*/", "", files,perl = T)
Abram Fleishman
  • 161
  • 1
  • 6