| Title: | Cross-Platform File System Operations Based on 'libuv' |
|---|---|
| Description: | A cross-platform interface to file system operations, built on top of the 'libuv' C library. |
| Authors: | Jim Hester [aut], Hadley Wickham [aut], Gábor Csárdi [aut, cre], libuv project contributors [cph] (libuv library), Joyent, Inc. and other Node contributors [cph] (libuv library), Posit Software, PBC [cph, fnd] (ROR: <https://ror.org/03wc8by49>) |
| Maintainer: | Gábor Csárdi <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.6.6.9000 |
| Built: | 2025-11-20 06:43:12 UTC |
| Source: | https://github.com/r-lib/fs |
file_copy() copies files.
link_copy() creates a new link pointing to the same location as the previous link.
dir_copy() copies the directory recursively at the new location.
file_copy(path, new_path, overwrite = FALSE)dir_copy(path, new_path, overwrite = FALSE)link_copy(path, new_path, overwrite = FALSE)file_copy(path, new_path, overwrite=FALSE)dir_copy(path, new_path, overwrite=FALSE)link_copy(path, new_path, overwrite=FALSE)
path | A character vector of one or more paths. |
new_path | A character vector of paths to the new locations. |
overwrite | Overwrite files if they exist. If this is |
The behavior ofdir_copy() differs slightly than that offile.copy() whenoverwrite = TRUE. The directory will always be copied tonew_path, evenif the name differs from the basename ofpath.
The new path (invisibly).
file_create("foo")file_copy("foo", "bar")try(file_copy("foo", "bar"))file_copy("foo", "bar", overwrite = TRUE)file_delete(c("foo", "bar"))dir_create("foo")# Create a directory and put a few files in itfiles <- file_create(c("foo/bar", "foo/baz"))file_exists(files)# Copy the directorydir_copy("foo", "foo2")file_exists(path("foo2", path_file(files)))# Create a link to the directorylink_create(path_abs("foo"), "loo")link_path("loo")link_copy("loo", "loo2")link_path("loo2")# Cleanupdir_delete(c("foo", "foo2"))link_delete(c("loo", "loo2"))file_create("foo")file_copy("foo","bar")try(file_copy("foo","bar"))file_copy("foo","bar", overwrite=TRUE)file_delete(c("foo","bar"))dir_create("foo")# Create a directory and put a few files in itfiles<- file_create(c("foo/bar","foo/baz"))file_exists(files)# Copy the directorydir_copy("foo","foo2")file_exists(path("foo2", path_file(files)))# Create a link to the directorylink_create(path_abs("foo"),"loo")link_path("loo")link_copy("loo","loo2")link_path("loo2")# Cleanupdir_delete(c("foo","foo2"))link_delete(c("loo","loo2"))
The functionsfile_create() anddir_create() ensure thatpath exists;if it already exists it will be left unchanged. That means that compared tofile.create(),file_create() will not truncate an existing file, andcompared todir.create(),dir_create() will silently ignore existingdirectories.
file_create(path, ..., mode = "u=rw,go=r")dir_create(path, ..., mode = "u=rwx,go=rx", recurse = TRUE, recursive)link_create(path, new_path, symbolic = TRUE)file_create(path,..., mode="u=rw,go=r")dir_create(path,..., mode="u=rwx,go=rx", recurse=TRUE, recursive)link_create(path, new_path, symbolic=TRUE)
path | A character vector of one or more paths. For |
... | Additional arguments passed to |
mode | If file/directory is created, what mode should it have? Links do not have mode; they inherit the mode of the file they link to. |
recurse | should intermediate directories be created if they do notexist? |
recursive | (Deprecated) If |
new_path | The path where the link should be created. |
symbolic | Boolean value determining if the link should be a symbolic(the default) or hard link. |
The path to the created object (invisibly).
file_create("foo")is_file("foo")# dir_create applied to the same path will failtry(dir_create("foo"))dir_create("bar")is_dir("bar")# file_create applied to the same path will failtry(file_create("bar"))# Cleanupfile_delete("foo")dir_delete("bar")file_create("foo")is_file("foo")# dir_create applied to the same path will failtry(dir_create("foo"))dir_create("bar")is_dir("bar")# file_create applied to the same path will failtry(file_create("bar"))# Cleanupfile_delete("foo")dir_delete("bar")
file_delete() andlink_delete() delete file and links. Compared tofile.remove they always fail if they cannot delete the object rather thanchanging return value or signalling a warning. If any inputs aredirectories, they are passed todir_delete(), sofile_delete() cantherefore be used to delete any filesystem object.
dir_delete() will first delete the contents of the directory, then removethe directory. Compared tounlink it will always throw an error if thedirectory cannot be deleted rather than being silent or signalling a warning.
file_delete(path)dir_delete(path)link_delete(path)file_delete(path)dir_delete(path)link_delete(path)
path | A character vector of one or more paths. |
The deleted paths (invisibly).
# create a directory, with some files and a link to itdir_create("dir")files <- file_create(path("dir", letters[1:5]))link <- link_create(path_abs("dir"), "link")# All files createddir_exists("dir")file_exists(files)link_exists("link")file_exists(link_path("link"))# Delete a filefile_delete(files[1])file_exists(files[1])# Delete the directory (which deletes the files as well)dir_delete("dir")file_exists(files)dir_exists("dir")# The link still exists, but what it points to does not.link_exists("link")dir_exists(link_path("link"))# Delete the linklink_delete("link")link_exists("link")# create a directory, with some files and a link to itdir_create("dir")files<- file_create(path("dir", letters[1:5]))link<- link_create(path_abs("dir"),"link")# All files createddir_exists("dir")file_exists(files)link_exists("link")file_exists(link_path("link"))# Delete a filefile_delete(files[1])file_exists(files[1])# Delete the directory (which deletes the files as well)dir_delete("dir")file_exists(files)dir_exists("dir")# The link still exists, but what it points to does not.link_exists("link")dir_exists(link_path("link"))# Delete the linklink_delete("link")link_exists("link")
dir_ls() is equivalent to thels command. It returns filenames as anamedfs_path character vector. The names are equivalent to the values,which is useful for passing onto functions likepurrr::map_dfr().
dir_info() is equivalent tols -l and a shortcut forfile_info(dir_ls()).
dir_map() applies a functionfun() to each entry in the path and returnsthe result in a list.
dir_walk() callsfun for its side-effect and returns the inputpath.
dir_ls( path = ".", all = FALSE, recurse = FALSE, type = "any", glob = NULL, regexp = NULL, invert = FALSE, fail = TRUE, ..., recursive)dir_map( path = ".", fun, all = FALSE, recurse = FALSE, type = "any", fail = TRUE)dir_walk( path = ".", fun, all = FALSE, recurse = FALSE, type = "any", fail = TRUE)dir_info( path = ".", all = FALSE, recurse = FALSE, type = "any", regexp = NULL, glob = NULL, fail = TRUE, ...)dir_ls( path=".", all=FALSE, recurse=FALSE, type="any", glob=NULL, regexp=NULL, invert=FALSE, fail=TRUE,..., recursive)dir_map( path=".", fun, all=FALSE, recurse=FALSE, type="any", fail=TRUE)dir_walk( path=".", fun, all=FALSE, recurse=FALSE, type="any", fail=TRUE)dir_info( path=".", all=FALSE, recurse=FALSE, type="any", regexp=NULL, glob=NULL, fail=TRUE,...)
path | A character vector of one or more paths. |
all | If |
recurse | If |
type | File type(s) to return, one or more of "any", "file", "directory","symlink", "FIFO", "socket", "character_device" or "block_device". |
glob | A wildcard aka globbing pattern (e.g. |
regexp | A regular expression (e.g. |
invert | If |
fail | Should the call fail (the default) or warn if a file cannot beaccessed. |
... | Additional arguments passed togrep. |
recursive | (Deprecated) If |
fun | A function, taking one parameter, the current path entry. |
dir_ls(R.home("share"), type = "directory")# Create a shorter linklink_create(system.file(package = "base"), "base")dir_ls("base", recurse = TRUE, glob = "*.R")# If you need the full paths input an absolute pathdir_ls(path_abs("base"))dir_map("base", identity)dir_walk("base", str)dir_info("base")# Cleanuplink_delete("base")dir_ls(R.home("share"), type="directory")# Create a shorter linklink_create(system.file(package="base"),"base")dir_ls("base", recurse=TRUE, glob="*.R")# If you need the full paths input an absolute pathdir_ls(path_abs("base"))dir_map("base", identity)dir_walk("base", str)dir_info("base")# Cleanuplink_delete("base")
Print contents of directories in a tree-like format
dir_tree(path = ".", recurse = TRUE, ...)dir_tree(path=".", recurse=TRUE,...)
path | A path to print the tree from |
recurse | If |
... | Arguments passed on to
|
file_exists(path) is a shortcut forfile_access(x, "exists")
dir_exists(path) andlink_exists(path) are similar but also check thatthe path is a directory or link, respectively. (file_exists(path) returnsTRUE ifpath exists and it is a directory. Useis_file() to check forfile (not directory) existence)
file_access(path, mode = "exists")file_exists(path)dir_exists(path)link_exists(path)file_access(path, mode="exists")file_exists(path)dir_exists(path)link_exists(path)
path | A character vector of one or more paths. |
mode | A character vector containing one or more of 'exists', 'read','write', 'execute'. |
Cross-compatibility warning: There is no executable bit onWindows. Checking a file for mode 'execute' on Windows, e.g.file_access(x, "execute") will always returnTRUE.
A logical vector, with names corresponding to the inputpath.
file_access("/")file_access("/", "read")file_access("/", "write")file_exists("WOMBATS")file_access("/")file_access("/","read")file_access("/","write")file_exists("WOMBATS")
Change file permissions
file_chmod(path, mode)file_chmod(path, mode)
path | A character vector of one or more paths. |
mode | A character representation of the mode, in either hexidecimal or symbolic format. |
Cross-compatibility warning: File permissions differ on Windowsfrom POSIX systems. Windows does not use an executable bit, so attemptingto change this will have no effect. Windows also does not have usergroups, so only the user permissions (u) are relevant.
file_create("foo", mode = "000")file_chmod("foo", "777")file_info("foo")$permissionsfile_chmod("foo", "u-x")file_info("foo")$permissionsfile_chmod("foo", "a-wrx")file_info("foo")$permissionsfile_chmod("foo", "u+wr")file_info("foo")$permissions# It is also vectorizedfiles <- c("foo", file_create("bar", mode = "000"))file_chmod(files, "a+rwx")file_info(files)$permissionsfile_chmod(files, c("644", "600"))file_info(files)$permissionsfile_create("foo", mode="000")file_chmod("foo","777")file_info("foo")$permissionsfile_chmod("foo","u-x")file_info("foo")$permissionsfile_chmod("foo","a-wrx")file_info("foo")$permissionsfile_chmod("foo","u+wr")file_info("foo")$permissions# It is also vectorizedfiles<- c("foo", file_create("bar", mode="000"))file_chmod(files,"a+rwx")file_info(files)$permissionsfile_chmod(files, c("644","600"))file_info(files)$permissions
Change owner or group of a file
file_chown(path, user_id = NULL, group_id = NULL)file_chown(path, user_id=NULL, group_id=NULL)
path | A character vector of one or more paths. |
user_id | The user id of the new owner, specified as a numeric ID orname. The R process must be privileged to change this. |
group_id | The group id of the new owner, specified as a numeric ID orname. |
Compared tofile.info() the full results of astat(2) system call arereturned and some columns are returned as S3 classes to make manipulationmore natural. On systems which do not support all metadata (such as Windows)default values are used.
file_info(path, fail = TRUE, follow = FALSE)file_size(path, fail = TRUE)file_info(path, fail=TRUE, follow=FALSE)file_size(path, fail=TRUE)
path | A character vector of one or more paths. |
fail | Should the call fail (the default) or warn if a file cannot beaccessed. |
follow | If |
A data.frame with metadata for each file. Columns returned are as follows.
path | The input path, as a |
type | The file type, as a factor of file types. |
size | The file size, as a |
permissions | The file permissions, as a |
modification_time | The time of last data modification, as aPOSIXct datetime. |
user | The file owner name - as a character vector. |
group | The file group name - as a character vector. |
device_id | The file device id - as a numeric vector. |
hard_links | The number of hard links to the file - as a numeric vector. |
special_device_id | The special device id of the file - as a numeric vector. |
inode | The inode of the file - as a numeric vector. |
block_size | The optimal block for the file - as a numeric vector. |
blocks | The number of blocks allocated for the file - as a numeric vector. |
flags | The user defined flags for the file - as an integer vector. |
generation | The generation number for the file - as a numeric vector. |
access_time | The time of last access - as aPOSIXct datetime. |
change_time | The time of last file status change - as aPOSIXct datetime. |
birth_time | The time when the inode was created - as aPOSIXct datetime. |
dir_info() to display file information for files in a givendirectory.
write.csv(mtcars, "mtcars.csv")file_info("mtcars.csv")# Files in the working directory modified more than 20 days agofiles <- file_info(dir_ls())files$path[difftime(Sys.time(), files$modification_time, units = "days") > 20]# Cleanupfile_delete("mtcars.csv")write.csv(mtcars,"mtcars.csv")file_info("mtcars.csv")# Files in the working directory modified more than 20 days agofiles<- file_info(dir_ls())files$path[difftime(Sys.time(), files$modification_time, units="days")>20]# Cleanupfile_delete("mtcars.csv")
Compared tofile.renamefile_move() always fails if it is unable to movea file, rather than signaling a Warning and returning an error code.
file_move(path, new_path)file_move(path, new_path)
path | A character vector of one or more paths. |
new_path | New file path. If Should either be the same length as |
The new path (invisibly).
file_create("foo")file_move("foo", "bar")file_exists(c("foo", "bar"))file_delete("bar")file_create("foo")file_move("foo","bar")file_exists(c("foo","bar"))file_delete("bar")
Open files or directories
file_show(path = ".", browser = getOption("browser"))file_show(path=".", browser= getOption("browser"))
path | A character vector of one or more paths. |
browser | a non-empty character string giving the name of theprogram to be used as the HTML browser. It should be in the PATH,or a full path specified. Alternatively, anR function to becalled to invoke the browser. Under Windows |
The directories that were opened (invisibly).
file_temp() returns the name which can be used as a temporary file.
file_temp(pattern = "file", tmp_dir = tempdir(), ext = "")file_temp_push(path)file_temp_pop()path_temp(...)file_temp(pattern="file", tmp_dir= tempdir(), ext="")file_temp_push(path)file_temp_pop()path_temp(...)
pattern | A character vector with the non-random portion of the name. |
tmp_dir | The directory the file will be created in. |
ext | The file extension of the temporary file. |
path | A character vector of one or more paths. |
... | Additional paths appended to the temporary directory by |
file_temp_push() can be used to supply deterministic entries in thetemporary file stack. This can be useful for reproducibility in like exampledocumentation and vignettes.
file_temp_pop() can be used to explicitly remove an entry from theinternal stack, however generally this is done instead by callingfile_temp().
path_temp() constructs a path within the session temporary directory.
path_temp()path_temp("does-not-exist")file_temp()file_temp(ext = "png")file_temp("image", ext = "png")# You can make the temp file paths deterministicfile_temp_push(letters)file_temp()file_temp()# Or explicitly remove valueswhile (!is.null(file_temp_pop())) nextfile_temp_pop()path_temp()path_temp("does-not-exist")file_temp()file_temp(ext="png")file_temp("image", ext="png")# You can make the temp file paths deterministicfile_temp_push(letters)file_temp()file_temp()# Or explicitly remove valueswhile(!is.null(file_temp_pop()))nextfile_temp_pop()
Like the touch POSIX utility this will create the file if it does notexist.
file_touch(path, access_time = Sys.time(), modification_time = access_time)file_touch(path, access_time= Sys.time(), modification_time= access_time)
path | A character vector of one or more paths. |
access_time,modification_time | The times to set, inputs will becoerced toPOSIXct objects. |
file_touch("foo", "2018-01-01")file_info("foo")[c("access_time", "modification_time", "change_time", "birth_time")]file_touch("foo","2018-01-01")file_info("foo")[c("access_time","modification_time","change_time","birth_time")]
Construct, manipulate and display vectors of file sizes. These are numericvectors, so you can compare them numerically, but they can also be comparedto human readable values such as '10MB'.
as_fs_bytes(x)fs_bytes(x)as_fs_bytes(x)fs_bytes(x)
x | A numeric or character vector. Character representations can useshorthand sizes (see examples). |
fs_bytes("1")fs_bytes("1K")fs_bytes("1Kb")fs_bytes("1Kib")fs_bytes("1MB")fs_bytes("1KB") < "1MB"sum(fs_bytes(c("1MB", "5MB", "500KB")))fs_bytes("1")fs_bytes("1K")fs_bytes("1Kb")fs_bytes("1Kib")fs_bytes("1MB")fs_bytes("1KB")<"1MB"sum(fs_bytes(c("1MB","5MB","500KB")))
Tidy file paths, character vectors which are coloured by file type oncapable terminals.
Colouring can be customized by setting theLS_COLORS environment variable,the format is the same as that read by GNU ls / dircolors.
Colouring of file paths can be disabled by settingLS_COLORS to an emptystring e.g.Sys.setenv(LS_COLORS = "").
as_fs_path(x)fs_path(x)as_fs_path(x)fs_path(x)
x | vector to be coerced to a fs_path object. |
https://geoff.greer.fm/lscolors,https://github.com/trapd00r/LS_COLORS,https://github.com/seebi/dircolors-solarized for some example coloursettings.
fs_perms() objects help one create and modify file permissions easily.They support both numeric input, octal and symbolic characterrepresentations. Compared tooctmode they support symbolic representationsand display the mode the same format asls on POSIX systems.
as_fs_perms(x, ...)fs_perms(x, ...)as_fs_perms(x,...)fs_perms(x,...)
x | An object which is to be coerced to a fs_perms object. Can be annumber or octal character representation, including symbolicrepresentations. |
... | Additional arguments passed to methods. |
On POSIX systems the permissions are displayed as a 9 character string withthree sets of three characters. Each set corresponds to the permissions forthe user, the group and other (or default) users.
If the first character of each set is a "r", the file is readable for thoseusers, if a "-", it is not readable.
If the second character of each set is a "w", the file is writable for thoseusers, if a "-", it is not writable.
The third character is more complex, and is the first of the followingcharacters which apply.
'S' If the character is part of the owner permissions and the file is notexecutable or the directory is not searchable by the owner, and theset-user-id bit is set.
'S' If the character is part of the group permissions and the file is notexecutable or the directory is not searchable by the group, and theset-group-id bit is set.
'T' If the character is part of the other permissions and the file is notexecutable or the directory is not searchable by others, and the 'sticky'(S_ISVTX) bit is set.
's' If the character is part of the owner permissions and the file isexecutable or the directory searchable by the owner, and the set-user-id bitis set.
's' If the character is part of the group permissions and the file isexecutable or the directory searchable by the group, and the set-group-idbit is set.
't' If the character is part of the other permissions and the file isexecutable or the directory searchable by others, and the ”sticky”(S_ISVTX) bit is set.
'x' The file is executable or the directory is searchable.
'-' If none of the above apply.Most commonly the third character is either 'x' or-.
On Windows the permissions are displayed as a 3 character string where thethird character is only- orx.
# Integer and numericfs_perms(420L)fs_perms(c(511, 420))# Octalfs_perms("777")fs_perms(c("777", "644"))# Symbolicfs_perms("a+rwx")fs_perms(c("a+rwx", "u+rw,go+r"))# Use the `&` and `|`operators to check for certain permissions(fs_perms("777") & "u+r") == "u+r"# Integer and numericfs_perms(420L)fs_perms(c(511,420))# Octalfs_perms("777")fs_perms(c("777","644"))# Symbolicfs_perms("a+rwx")fs_perms(c("a+rwx","u+rw,go+r"))# Use the `&` and `|`operators to check for certain permissions(fs_perms("777")&"u+r")=="u+r"
These functions use the GETPWENT(3) and GETGRENT(3) system calls to queryusers and groups respectively.
group_ids()user_ids()group_ids()user_ids()
They return their results in adata.frame. On windows bothfunctions return an emptydata.frame because windows does not have useror group ids.
# list first 6 groupshead(group_ids())# list first 6 usershead(user_ids())# list first 6 groupshead(group_ids())# list first 6 usershead(user_ids())
Test if a path is an absolute path
is_absolute_path(path)is_absolute_path(path)
path | A character vector of one or more paths. |
is_absolute_path("/foo")is_absolute_path("C:\\foo")is_absolute_path("\\\\myserver\\foo\\bar")is_absolute_path("foo/bar")is_absolute_path("/foo")is_absolute_path("C:\\foo")is_absolute_path("\\\\myserver\\foo\\bar")is_absolute_path("foo/bar")
This function checks whether a given directory is empty or not.
is_dir_empty(path)is_dir_empty(path)
path | A character string specifying the path to the directory to check. |
A logical value. ReturnsTRUE if the directory is empty,FALSE otherwise.
## Not run: is_dir_empty("path/to/empty/directory") # Returns TRUEis_dir_empty("path/to/non-empty/directory") # Returns FALSE## End(Not run)## Not run:is_dir_empty("path/to/empty/directory")# Returns TRUEis_dir_empty("path/to/non-empty/directory")# Returns FALSE## End(Not run)
Functions to test for file types
is_file(path, follow = TRUE)is_dir(path, follow = TRUE)is_link(path)is_file_empty(path, follow = TRUE)is_file(path, follow=TRUE)is_dir(path, follow=TRUE)is_link(path)is_file_empty(path, follow=TRUE)
path | A character vector of one or more paths. |
follow | If |
A named logical vector, where the names give the paths. If the givenobject does not exist,NA is returned.
file_exists(),dir_exists() andlink_exists() if you wantto ensure that the path also exists.
dir_create("d")file_create("d/file.txt")dir_create("d/dir")link_create(path(path_abs("d"), "file.txt"), "d/link")paths <- dir_ls("d")is_file(paths)is_dir(paths)is_link(paths)# Cleanupdir_delete("d")dir_create("d")file_create("d/file.txt")dir_create("d/dir")link_create(path(path_abs("d"),"file.txt"),"d/link")paths<- dir_ls("d")is_file(paths)is_dir(paths)is_link(paths)# Cleanupdir_delete("d")
Read the value of a symbolic link
link_path(path)link_path(path)
path | A character vector of one or more paths. |
A tidy path to the object the link points to.
file_create("foo")link_create(path_abs("foo"), "bar")link_path("bar")# Cleanupfile_delete(c("foo", "bar"))file_create("foo")link_create(path_abs("foo"),"bar")link_path("bar")# Cleanupfile_delete(c("foo","bar"))
path() constructs a relative path,path_wd() constructs an absolute pathfrom the current working directory.
path(..., ext = "")path_wd(..., ext = "")path(..., ext="")path_wd(..., ext="")
... | character vectors, if any values are NA, the result will also beNA. The paths follow the recycling rules used in the tibble package,namely that only length 1 arguments are recycled. |
ext | An optional extension to append to the generated path. |
path_home(),path_package() for functions to construct pathsrelative to the home and package directories respectively.
path("foo", "bar", "baz", ext = "zip")path("foo", letters[1:3], ext = "txt")path("foo","bar","baz", ext="zip")path("foo", letters[1:3], ext="txt")
path_expand() performs tilde expansion on a path, replacing instances of~ or~user with the user's home directory.
path_home() constructs a path within the expanded users home directory,calling it withno arguments can be useful to verify what fs considers thehome directory.
path_expand_r() andpath_home_r() are equivalents which always use R'sdefinition of the home directory.
path_expand(path)path_expand_r(path)path_home(...)path_home_r(...)path_expand(path)path_expand_r(path)path_home(...)path_home_r(...)
path | A character vector of one or more paths. |
... | Additional paths appended to the home directory by |
path_expand() differs frombase::path.expand() in the interpretation ofthe home directory of Windows. In particularpath_expand() uses the pathset in theUSERPROFILE environment variable and, if unset, then usesHOMEDRIVE/HOMEPATH.
In contrastbase::path.expand() first checks forR_USER thenHOME,which in the default configuration of R on Windows are both set to the user'sdocument directory, e.g.C:\\Users\\username\\Documents.base::path.expand() also does not support~otheruser syntax on Windows,whereaspath_expand() does support this syntax on all systems.
This definition makes fs more consistent with the definition of homedirectory used on Windows in other languages, such aspythonandrust. Thisis also more compatible with external tools such as git and ssh, both ofwhich put user-level files inUSERPROFILE by default. It also allows you towrite portable paths, such as~/Desktop that points to the Desktop locationon Windows, macOS and (most) Linux systems.
Users can set theR_FS_HOME environment variable to override thedefinitions on any platform.
R for Windows FAQ - 2.14for behavior ofbase::path.expand().
# Expand a pathpath_expand("~/bin")# You can use `path_home()` without arguments to see what is being used as# the home diretory.path_home()path_home("R")# This will likely differ from the above on Windowspath_home_r()# Expand a pathpath_expand("~/bin")# You can use `path_home()` without arguments to see what is being used as# the home diretory.path_home()path_home("R")# This will likely differ from the above on Windowspath_home_r()
path_file() returns the filename portion of the path
path_dir() returns the directory portion of the path
path_ext() returns the last extension (if any) for a path
path_ext_remove() removes the last extension and returns the rest ofthe path
path_ext_set() replaces the extension with a new extension. If there isno existing extension the new extension is appended
path_file(path)path_dir(path)path_ext(path)path_ext_remove(path)path_ext_set(path, ext)path_ext(path) <- valuepath_file(path)path_dir(path)path_ext(path)path_ext_remove(path)path_ext_set(path, ext)path_ext(path)<- value
path | A character vector of one or more paths. |
ext,value | The new file extension. |
Note because these are not full file paths they return regular charactervectors, notfs_path objects.
base::basename(),base::dirname()
path_file("dir/file.zip")path_dir("dir/file.zip")path_ext("dir/file.zip")path_ext("file.tar.gz")path_ext_remove("file.tar.gz")# Only one level of extension is removedpath_ext_set(path_ext_remove("file.tar.gz"), "zip")path_file("dir/file.zip")path_dir("dir/file.zip")path_ext("dir/file.zip")path_ext("file.tar.gz")path_ext_remove("file.tar.gz")# Only one level of extension is removedpath_ext_set(path_ext_remove("file.tar.gz"),"zip")
Filter paths
path_filter(path, glob = NULL, regexp = NULL, invert = FALSE, ...)path_filter(path, glob=NULL, regexp=NULL, invert=FALSE,...)
path | A character vector of one or more paths. |
glob | A wildcard aka globbing pattern (e.g. |
regexp | A regular expression (e.g. |
invert | If |
... | Additional arguments passed togrep. |
path_filter(c("foo", "boo", "bar"), glob = "*oo")path_filter(c("foo", "boo", "bar"), glob = "*oo", invert = TRUE)path_filter(c("foo", "boo", "bar"), regexp = "b.r")path_filter(c("foo","boo","bar"), glob="*oo")path_filter(c("foo","boo","bar"), glob="*oo", invert=TRUE)path_filter(c("foo","boo","bar"), regexp="b.r")
All functions apart frompath_real() are purely path computations, so thefiles in question do not need to exist on the filesystem.
path_real(path)path_split(path)path_join(parts)path_abs(path, start = ".")path_norm(path)path_rel(path, start = ".")path_common(path)path_has_parent(path, parent)path_real(path)path_split(path)path_join(parts)path_abs(path, start=".")path_norm(path)path_rel(path, start=".")path_common(path)path_has_parent(path, parent)
path | A character vector of one or more paths. |
parts | A character vector or a list of character vectors, correspondingto split paths. |
start | A starting directory to compute the path relative to. |
parent | The parent path. |
The new path(s) in anfs_path object, which is a character vectorthat also has classfs_path. Exceptpath_split(), which returns a listof character vectors of path components.
path_real(): returns the canonical path, eliminating any symboliclinks and the special references~,~user,., and.., , i.e. itcallspath_expand() (literally) andpath_norm() (effectively).
path_split(): splits paths into parts.
path_join(): joins parts together. The inverse ofpath_split().Seepath() to concatenate vectorized strings into a path.
path_abs(): returns a normalized, absolute version of a path.
path_norm(): eliminates. references and rationalizes up-level.. references, soA/./B andA/foo/../B both becomeA/B, but../Bis not changed. If one of the paths is a symbolic link, this may change themeaning of the path, so consider usingpath_real() instead.
path_rel(): computes the path relative to thestart path,which can be either an absolute or relative path.
path_common(): finds the common parts of two (or more) paths.
path_has_parent(): determine if a path has a given parent.
path_expand() for expansion of user's home directory.
dir_create("a")file_create("a/b")link_create(path_abs("a"), "c")# Realize the pathpath_real("c/b")# Split a pathparts <- path_split("a/b")parts# Join it togetherpath_join(parts)# Find the absolute pathpath_abs("..")# Normalize a pathpath_norm("a/../b\\c/.")# Compute a relative pathpath_rel("/foo/abc", "/foo/bar/baz")# Find the common path between multiple pathspath_common(c("/foo/bar/baz", "/foo/bar/abc", "/foo/xyz/123"))# Cleanupdir_delete("a")link_delete("c")dir_create("a")file_create("a/b")link_create(path_abs("a"),"c")# Realize the pathpath_real("c/b")# Split a pathparts<- path_split("a/b")parts# Join it togetherpath_join(parts)# Find the absolute pathpath_abs("..")# Normalize a pathpath_norm("a/../b\\c/.")# Compute a relative pathpath_rel("/foo/abc","/foo/bar/baz")# Find the common path between multiple pathspath_common(c("/foo/bar/baz","/foo/bar/abc","/foo/xyz/123"))# Cleanupdir_delete("a")link_delete("c")
path_package differs fromsystem.file() in that it always returns anerror if the package does not exist. It also returns a different error ifthe file within the package does not exist.
path_package(package, ...)path_package(package,...)
package | Name of the package to in which to search |
... | Additional paths appended to the package path by |
path_package() also automatically works with packages loaded with devtoolseven if thepath_package() call comes from a different package.
path_package("base")path_package("stats")path_package("base", "INDEX")path_package("splines", "help", "AnIndex")path_package("base")path_package("stats")path_package("base","INDEX")path_package("splines","help","AnIndex")
path_sanitize() removes the following:
Unix reserved filenames (. and..)
Trailing periods and spaces (invalid on Windows)
Windows reserved filenames (CON,PRN,AUX,NUL,COM1,COM2,COM3, COM4,COM5,COM6,COM7,COM8,COM9,LPT1,LPT2,LPT3,LPT4,LPT5,LPT6, LPT7,LPT8, andLPT9)The resulting string is then truncated to255 bytes in length
path_sanitize(filename, replacement = "")path_sanitize(filename, replacement="")
filename | A character vector to be sanitized. |
replacement | A character vector used to replace invalid characters. |
https://www.npmjs.com/package/sanitize-filename, upon which thisfunction is based.
# potentially unsafe stringstr <- "~/.\u0001ssh/authorized_keys"path_sanitize(str)path_sanitize("..")# potentially unsafe stringstr<-"~/.\u0001ssh/authorized_keys"path_sanitize(str)path_sanitize("..")
path_select_components() allows to select individual components fromanfs_path object via their index.
path_select_components(path, index, from = c("start", "end"))path_select_components(path, index, from= c("start","end"))
path | A path of class |
index | An integer vector of path positions. (A negative index will workaccording to R's usual subsetting rules.) |
from | A character of either |
path_select_components() is vectorized.
Anfs_path object, which is a character vector that also has classfs_path.
path <- fs::path("some", "simple", "path", "to", "a", "file.txt")path_select_components(path, 1:3)path_select_components(path, 1:3, "end")path_select_components(path, -1, "end")path_select_components(path, 6)path<- fs::path("some","simple","path","to","a","file.txt")path_select_components(path,1:3)path_select_components(path,1:3,"end")path_select_components(path,-1,"end")path_select_components(path,6)
Untidy paths are all different, tidy paths are all the same.Tidy paths always use/ to delimit directories, never havemultiple/ or trailing/ and have colourised output based on the filetype.
path_tidy(path)path_tidy(path)
path | A character vector of one or more paths. |
Anfs_path object, which is a character vector that also has classfs_path