class IO::Path
Error ReportCollection examples

File or directory path

IO::Path is the workhorse of IO operations.

Conceptually, an IO::Path object consists of a volume, a directory, and a basename. It supports both purely textual operations, and operations that access the filesystem, e.g. to resolve a path, or to read all the content of a file.

## attribute path

Read-only. Returns the string the object was constructed from or the value of $SPEC.join($volume, $dirname,$basename) if multi-part version of .new was used. NOTE: this does not include the $.CWD; see IO::Path.absolute and IO::Path.relative for stringification options that include $.CWD.

NOTE: Implementations may cache operations done with this attribute, so modifying its value (via cloning or Proxy) is NOT recommended and may result in broken IO::Path objects. Create a new IO::Path object instead.

## method ACCEPTS

Defined as:

Coerces the argument to IO::Path, if necessary. Returns True if .absolute method on both paths returns the same string. NOTE: it's possible for two paths that superficially point to the same resource to NOT smartmatch as True, if they were constructed differently and were never fully resolved:

The reason is the two paths above may point to different resources when fully resolved (e.g. if foo is a symlink). Resolve the paths before smartmatching to check they point to same resource:

## method basename

Defined as:

Returns the basename part of the path object, which is the name of the filesystem object itself that is referenced by the path.

Note that in IO::Spec::Win32 semantics, the basename of a Windows share is \, not the name of the share itself:

Defined as:

Concatenates a path fragment to the invocant and returns the resultant IO::Path. If adding ../ to paths that end with a file, you may need to call resolve for the resultant path to be accessible by other IO::Path methods like dir or open. See also sibling and parent.

## method child

Defined as:

Alias for .add. NOTE: This method has been deprecated as of the 6.d version, and will be removed in the future. For any new code, please use .add

## method cleanup

Defined as:

Returns a new path that is a canonical representation of the invocant path, cleaning up any extraneous path parts:

Note that no filesystem access is made. See also resolve.

## method comb

Defined as:

Opens the file and processes its contents the same way Str.comb does, taking the same arguments. Implementations may slurp the file in its entirety when this method is called.

## method split

Defined as:

Opens the file and processes its contents the same way Str.split does, taking the same arguments. Implementations may slurp the file in its entirety when this method is called.

## method extension

Defined as:

Returns the extension consisting of $parts parts (defaults to 1), where a "part" is defined as a dot followed by possibly-empty string up to the end of the string, or previous part. That is "foo.tar.gz" has an extension of two parts: first part is "gz" and second part is "tar" and calling "foo.tar.gz".IO.extension: :2parts gives "tar.gz". If an extension with the specified number of $parts is not found, returns an empty string.

$parts can be a Range, specifying the minimum number of parts and maximum number of parts the extension should have. The routine will attempt to much the most parts it can. If $parts range's endpoints that are smaller than 0 they'll be treated as 0; implementations may treat endpoints larger than 2⁶³-1 as 2⁶³-1. Ranges with NaN or Str endpoints will cause an exception to be thrown.

## method gist

Defined as:

Returns a string, part of which contains either the value of .absolute (if path is absolute) or .path. Note that no escaping of special characters is made, so e.g. "\b" means a path contains a backslash and letter "b", not a backspace.

Defined as:

## method relative

Defined as:

Returns a new Str object with the path relative to the $base. If $base is not provided, $*CWD is used in its place. If the invocant is not an absolute path, it's first made to be absolute using the .CWD attribute the object was created with, and then is made relative to $base.

## method parent

Defined as:

Returns the parent path of the invocant. Note that no actual filesystem access is made, so the returned parent is physical and not the logical parent of symlinked directories.

If $level is specified, the call is equivalent to calling .parent() $level times:

## method resolve

Defined as:

Returns a new IO::Path object with all symbolic links and references to the parent directory (..) resolved. This means that the filesystem is examined for each directory in the path, and any symlinks found are followed.

If :$completely, which defaults to False, is set to a true value, the method will fail with X::IO::Resolve if it cannot completely resolve the path, otherwise, it will resolve as much as possible, and will merely perform cleanup of the rest of the path. The last part of the path does NOT have to exist to :$completely resolve the path.

NOTE: Currently (April 2017) this method doesn't work correctly on all platforms, e.g. Windows, since resolve assumes POSIX semantics.

## routine dir

Defined as:

Returns the contents of a directory as a lazy list of IO::Path objects representing relative paths, filtered by smartmatching their names (as strings) against the :test parameter. The path of returned files will be absolute or relative depending on what $path is. Since the tests are performed against Str arguments, not IO, the tests are executed in the $*CWD, instead of the target directory. When testing against file test operators, this won't work:

while this will:

NOTE: a dir call opens a directory for reading, which counts towards maximum per-process open files for your program. Be sure to exhaust returned Seq before doing something like recursively performing more dir calls. You can exhaust it by assigning to a @-sigiled variable or simply looping over it. Note how examples below push further dirs to look through into an Array, rather than immediately calling dir on them. See also IO::Dir module that gives you finer control over closing dir handles.

Examples:

An example program that lists all files and directories recursively:

A lazy way to find the first three files ending in ".p6" recursively starting from the current directory:

## File test operators

For most file tests, you can do a smartmatch ~~ or you can call a method. You don't need to actually open a filehandle in the traditional way (although you can) to do a filetest. You can simply append .IO to the filename and smartmatch it to a test adverb. For instance, here is how to check whether a file is readable using smartmatch:

File tests include:

These tests will not cache the results of earlier test executions.

Smartmatching on Pairs can be used to perform multiple tests at once:

All of the above tests can be used as methods (without the colon), though method tests may throw X::IO::DoesNotExist as documented below. Three tests only exist as methods: accessed, changed and modified.

## method spurt

Defined as:

Opens the file path for writing, and writes all of the $data into it. File will be closed, afterwards. Will fail if it cannot succeed for any reason. The $data can be any Cool type or any Blob type. Arguments are as follows:

• :$enc — character encoding of the data. Takes same values as :$enc in IO::Handle.open. Defaults to utf8. Ignored if $data is a Blob. • :$append — open the file in append mode, preserving existing contents, and appending data to the end of the file.

## method mkdir

Defined as:

Creates a new directory, including its parent directories, as needed (similar to *nix utility mkdir with -p option). That is, mkdir "foo/bar/ber/meow" will create foo, foo/bar, and foo/bar/ber directories as well if they do not exist.

Returns the IO::Path object pointing to the newly created directory on success; fails with X::IO::Mkdir if directory cannot be created.

See also mode for explanation and valid values for $mode. ## routine rmdir Defined as: Remove the invocant, or in sub form, all of the provided directories in the given list, which can contain any Cool object. Only works on empty directories. Method form returns True on success and returns a Failure of type X::IO::Rmdir if the directory cannot be removed (e.g. the directory is not empty, or the path is not a directory). Subroutine form returns a list of directories that were successfully deleted. To delete non-empty directory, see rmtree in File::Directory::Tree module. ## method chmod Defined as: Changes the POSIX permissions of a file or directory to $mode. Returns True on success; on failure, fails with X::IO::Chmod.

The mode is expected as an integer following the standard numeric notation, and is best written as an octal number:

Make sure you don't accidentally pass the intended octal digits as a decimal number (or string containing a decimal number):

## routine rename

Defined as:

Renames a file or directory. Returns True on success; fails with X::IO::Rename if :$createonly is True and the $to path already exists or if the operation failed for some other reason.

Note: some renames will always fail, such as when the new name is on a different storage device. See also: move.

## routine copy

Defined as:

Copies a file. Returns True on success; fails with X::IO::Copy if :$createonly is True and the $to path already exists or if the operation failed for some other reason, such as when $to and $from are the same file.

## routine move

Defined as:

Copies a file and then removes the original. If removal fails, it's possible to end up with two copies of the file. Returns True on success; fails with X::IO::Move if :$createonly is True and the $to path already exists or if the operation failed for some other reason, such as when $to and $from are the same file.

To avoid copying, you can use rename, if the files are on the same storage device. It also works with directories, while move does not.

## method Numeric

Defined as:

Coerces .basename to Numeric. Fails with X::Str::Numeric if base name is not numerical.

## method Int

Defined as:

Coerces .basename to Int. Fails with X::Str::Numeric if base name is not numerical.

Defined as:

Create a new symbolic link $link to existing $target. Returns True on success; fails with X::IO::Symlink if the symbolic link could not be created. If $target does not exist, creates a dangling symbolic link. symlink creates a symbolic link using an absolute path by default. To create a relative symlink set the absolute parameter to False e.g. :!absolute. This flag was introduced in Rakudo version 2020.11. To create a hard link, see link. Note: on Windows, creation of symbolic links may require escalated privileges. Defined as: Create a new hard link $link to existing \$target. Returns True on success; fails with X::IO::Link if the hard link could not be created. To create a symbolic link, see symlink.

Defined as:

Delete all specified ordinary files, links, or symbolic links for which there are privileges to do so. See rmdir to delete directories.

The subroutine form returns the names of all the files in the list, excluding those for which the filesystem raised some error; since trying to delete a file that does not exist does not raise any error at that level, this list will include the names of the files in the list that do not exist.

The method form returns True on success, or fails with X::IO::Unlink if the operation could not be completed. If the file to be deleted does not exist, the routine treats it as success.

## method IO

Defined as:

Returns the invocant.

## method SPEC

Defined as:

Returns the IO::Spec object that was (implicitly) specified at object creation time.

# File timestamp retrieval

There are also 3 methods for fetching the 3 timestamps of a file (inode), on Operating Systems where these are available:

## method modified

Returns an Instant object indicating when the content of the file was last modified. Compare with changed.

## method accessed

Return an Instant object representing the timestamp when the file was last accessed. Note: depending on how the filesystem was mounted, the last accessed time may not update on each access to the file, but only on the first access after modifications.

## method changed

Returns an Instant object indicating the metadata of the file or directory was last changed (e.g. permissions, or files created/deleted in directory). Compare with modified.

# File permissions retrieval

## method mode

Return an IntStr object representing the POSIX permissions of a file. The Str part of the result is the octal representation of the file permission, like the form accepted by the chmod(1) utility.

The result of this can be used in the other methods that take a mode as an argument.