Making a Path
First lets initialize a new path object.
root <- Path$new(system.file("", package = "pathlibr", mustWork = TRUE))
And lets view the new path
root$show
#> [1] "/private/var/folders/xl/014m21yx3x52_b9hcr7sztz80000gs/T/Rtmp9gT9Yx/Rinst813f1c8bc5fa/pathlibr/"
So far so good, we were able to initialize a Path object at our package install root.
Now how do we use it?
Navigating with your path
Lets go down a level, and examine our example vignette data.
Here, we use the dir binding, followed by .
Think of . as in, how file-systems represent the current directory.
This is actually just a shortcut for dir or ls.
eg <- root$dir$example
print(glue("using dir: {eg$show}"))
#> using dir: /private/var/folders/xl/014m21yx3x52_b9hcr7sztz80000gs/T/Rtmp9gT9Yx/Rinst813f1c8bc5fa/pathlibr//example
eg <- root$.$example
print(glue("using '.': {eg$show}"))
#> using '.': /private/var/folders/xl/014m21yx3x52_b9hcr7sztz80000gs/T/Rtmp9gT9Yx/Rinst813f1c8bc5fa/pathlibr//example
It’s important to note that path$. is actually returning a named list of files in the directory, and that though these files might look like strings when printed, they’re actually new Path objects.
Because of this, we’re able to chain subsequent $. commands.
Let’s see that in action.
file <- eg$.$path$.$to$.$file1.txt
file
#> [1] "/private/var/folders/xl/014m21yx3x52_b9hcr7sztz80000gs/T/Rtmp9gT9Yx/Rinst813f1c8bc5fa/pathlibr//example/path/to/file1.txt"
Great, so how do we navigate to file1.txt’s sibling, file2.txt?
We could use the path$parent binding to return the Path object corresponding to the directory example/path/to/,
as you may have guessed, we can use a shortcut alias, path$.. to navigate up.
file$parent
#> [1] "/private/var/folders/xl/014m21yx3x52_b9hcr7sztz80000gs/T/Rtmp9gT9Yx/Rinst813f1c8bc5fa/pathlibr//example/path/to"
file$..
#> [1] "/private/var/folders/xl/014m21yx3x52_b9hcr7sztz80000gs/T/Rtmp9gT9Yx/Rinst813f1c8bc5fa/pathlibr//example/path/to"
Now that we’re able to move upwards, we can access the sibling
file2 <- file$..$.$file2.txt
file2$show
#> [1] "/private/var/folders/xl/014m21yx3x52_b9hcr7sztz80000gs/T/Rtmp9gT9Yx/Rinst813f1c8bc5fa/pathlibr//example/path/to/file2.txt"
I wonder what’s inside these files? To find out, we should read them.
It’s important to notes that we should use this $show binding to return the path as a string when giving it to IO functions.
Inconvenient, I know (I’m going to work on that)
directory <- file$..
for (f in c("file1.txt", "file2.txt")){
print(glue("{f}:\n"))
directory$.[[f]]$show %>% readLines() %>% cat()
print(glue("\n"))
}
#> file1.txt:
#> I am the first file!
#> file2.txt:
#> I am the second file!