Skip to contents

Splits a file path into its components such as directory, file name, and extension. The function is OS-aware and works on both Windows and Unix-like systems.

Usage

splitPath(path, lastIsFile = NULL)

Arguments

path

a character vector of file paths.

lastIsFile

logical; if TRUE, the last component of path is treated as a file name. If FALSE, it is treated as part of the directory path. If NULL (default), the function determines this automatically based on whether the path ends with a path separator.

Value

a list with the following components (each a vector of the same length as path):

normpath

normalized path as returned by normalizePath().

drive

drive letter on Windows systems (e.g., "C:"), otherwise NA.

dirname

directory path without drive letter, including trailing separator.

fullfilename

full file name including extension (if applicable).

fullpath

full directory path including drive letter and trailing separator.

filename

file name without extension.

extension

file extension without leading dot.

Details

The function uses basename() and dirname() for platform-independent path handling. File name and extension are extracted using tools::file_path_sans_ext() and tools::file_ext().

If lastIsFile = FALSE, the path is treated as a directory and file-related components (fullfilename, filename, extension) are returned as NA.

Examples

splitPath("C:/temp/file.txt")
#> $normpath
#> [1] "C:/temp/file.txt"
#> 
#> $drive
#> [1] NA
#> 
#> $dirname
#> [1] "C:/temp/"
#> 
#> $fullfilename
#> [1] "file.txt"
#> 
#> $fullpath
#> [1] "C:/temp/"
#> 
#> $filename
#> [1] "file"
#> 
#> $extension
#> [1] "txt"
#> 

splitPath("/home/user/data.csv")
#> $normpath
#> [1] "/home/user/data.csv"
#> 
#> $drive
#> [1] NA
#> 
#> $dirname
#> [1] "/home/user/"
#> 
#> $fullfilename
#> [1] "data.csv"
#> 
#> $fullpath
#> [1] "/home/user/"
#> 
#> $filename
#> [1] "data"
#> 
#> $extension
#> [1] "csv"
#> 

# treat as directory
splitPath("/home/user/folder/", lastIsFile = FALSE)
#> $normpath
#> [1] "/home/user/folder/"
#> 
#> $drive
#> [1] NA
#> 
#> $dirname
#> [1] "/home/user/folder//"
#> 
#> $fullfilename
#> [1] NA
#> 
#> $fullpath
#> [1] "/home/user/folder//"
#> 
#> $filename
#> [1] NA
#> 
#> $extension
#> [1] NA
#>