class IO::Path

File or directory path
class IO::Path is Cool does IO { }

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.

At creation, each IO::Path object is given information about the current working directory the path might be relative to using the $.CWD attribute (defaults to $*CWD), as well as what operating system semantics should be used for path manipulation using the special IO::Spec type given in the $.SPEC attribute.

The $.SPEC defaults to the value of $*SPEC, which uses the object suitable for the operating system the code is currently running on. This is the default most code will be comfortable with.

In certain situations, e.g. testing, you may wish to force $*SPEC to use one of the specific SPEC modules: IO::Spec::Unix, IO::Spec::Win32, IO::Spec::Cygwin, and IO::Spec::QNX, or to create IO::Path objects via shortcut subclasses IO::Path::Unix, IO::Path::Win32, IO::Path::Cygwin, and IO::Path::QNX that pre-set the $.SPEC attribute for you.

The rest of this document silently assumes Unix semantics in its examples, unless stated otherwise.

Methods

method new

multi method new(Str:D $path, IO::Spec :$SPEC = $*SPEC, Str() :$CWD = $*CWD)
multi method new(
    :$basename!, :$dirname = '.', :$volume = ''
    IO::Spec :$SPEC = $*SPEC, Str() :$CWD = $*CWD
)

Creates a new IO::Path object from a path string (which is being parsed for volume, directory name and basename), or from volume, directory name and basename passed as named arguments.

The path's operation will be performed using :$SPEC semantics (defaults to current $*SPEC) and will use :$CWD as the directory the path is relative to (defaults to $*CWD).

If $path includes the null byte, it will throw an Exception with a "Cannot use null character (U+0000) as part of the path" message.

attribute CWD

IO::Path.new("foo", :CWD</home/camelia>)
        .CWD.say; # OUTPUT: «/home/camelia␤»

Read-only. Contains implicit or explicit value of :$CWD argument to .new.

attribute SPEC

IO::Path.new("foo", :SPEC(IO::Spec::Unix.new))\
        .SPEC.^name.say; # OUTPUT: «IO::Spec::Unix␤»

Read-only. Contains implicit or explicit value of :$SPEC argument to .new.

attribute path

IO::Path.new("foo").path.say; # OUTPUT: «foo␤»

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

multi method ACCEPTS(IO::Path:D: Cool:D $other --> Bool:D)

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:

say "foo/../bar".IO ~~ "bar".IO # False

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:

say "foo/../bar".IO.resolve(:completely) ~~ "bar".IO.resolve(:completely) # True

method basename

method basename(IO::Path:D:)

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

"docs/README.pod".IO.basename.say; # OUTPUT: «README.pod␤»
    "/tmp/".IO.basename.say;           # OUTPUT: «tmp␤»

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

IO::Path::Win32.new('//server/share').basename.say; # OUTPUT: «\␤»

method add

method add(IO::Path:D: Str() $what --> IO::Path:D)

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.

"foo/bar".IO.mkdir;
    "foo/bar".IO.add("meow")    .resolve.relative.say; # OUTPUT: «foo/bar/meow␤»
    "foo/bar".IO.add("/meow")   .resolve.relative.say; # OUTPUT: «foo/bar/meow␤»
    "foo/bar".IO.add("meow.txt").resolve.relative.say; # OUTPUT: «foo/bar/meow.txt␤»
    "foo/bar".IO.add("../meow") .resolve.relative.say; # OUTPUT: «foo/meow␤»
    "foo/bar".IO.add("../../")  .resolve.relative.say; # OUTPUT: «.␤»
method add(IO::Path:D: *@parts --> IO::Path:D)

As of release 2021.07 of the Rakudo compiler, it is also possible to specify multiple parts to be added to a path.

"foo".IO.add(<bar baz>).resolve.relative.say;      # OUTPUT: «foo/bar/baz␤»

method child

method child(IO::Path:D: Str() $childname --> IO::Path:D)

Alias for .add.

method cleanup

method cleanup(IO::Path:D: --> IO::Path:D)

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

"foo/./././..////bar".IO.cleanup.say;      # OUTPUT: «"foo/../bar".IO␤»
    IO::Path::Win32.new("foo/./././..////bar")
        .cleanup.say; "foo\..\bar".IO;         # OUTPUT: «"foo\..\bar".IO␤»

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

method comb

method comb(IO::Path:D: |args --> Seq:D)

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

method split(IO::Path:D: |args --> Seq:D)

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

multi method extension(IO::Path:D:                                         --> Str:D)
    multi method extension(IO::Path:D:               Int :$parts               --> Str:D)
    multi method extension(IO::Path:D:             Range :$parts               --> Str:D)
    multi method extension(IO::Path:D: Str $subst,   Int :$parts, Str :$joiner --> IO::Path:D)
    multi method extension(IO::Path:D: Str $subst, Range :$parts, Str :$joiner --> IO::Path:D)

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.

If $subst is provided, the extension will be instead replaced with $subst and a new IO::Path object will be returned. It will be joined to the file's name with $joiner, which defaults to an empty string when $subst is an empty string and to "." when $subst is not empty. Note: if as the result of replacement the basename of the path ends up being empty, it will be assumed to be . (a single dot).

# Getting an extension:
    say "foo.tar.gz".IO.extension;               # OUTPUT: «gz␤»
    say "foo.tar.gz".IO.extension: :2parts;      # OUTPUT: «tar.gz␤»
    say "foo.tar.gz".IO.extension: :parts(^5);   # OUTPUT: «tar.gz␤»
    say "foo.tar.gz".IO.extension: :parts(0..1); # OUTPUT: «gz␤»
# Replacing an extension
    say "foo.tar.gz".IO.extension: '';                # OUTPUT: «"foo.tar".IO␤»
    say "foo.tar.gz".IO.extension: 'ZIP';             # OUTPUT: «"foo.tar.ZIP".IO␤»
    say "foo.tar.gz".IO.extension: 'ZIP', :0parts;    # OUTPUT: «"foo.tar.gz.ZIP".IO␤»
    say "foo.tar.gz".IO.extension: 'ZIP', :2parts;    # OUTPUT: «"foo.ZIP".IO␤»
    say "foo.tar.gz".IO.extension: 'ZIP', :parts(^5); # OUTPUT: «"foo.ZIP".IO␤»
# Replacing an extension using non-standard joiner:
    say "foo.tar.gz".IO.extension: '',    :joiner<_>;  # OUTPUT: «"foo.tar_".IO␤»
    say "foo.tar.gz".IO.extension: 'ZIP', :joiner<_>;  # OUTPUT: «"foo.tar_ZIP".IO␤»
    say "foo.tar.gz".IO.extension: 'ZIP', :joiner<_>,
                                           :2parts;     # OUTPUT: «"foo_ZIP".IO␤»
    say "foo.tar.gz".IO.extension: 'ZIP', :joiner<_>,
                                           :parts(^5);  # OUTPUT: «"foo_ZIP".IO␤»
# EDGE CASES:
# There is no 5-part extension, so returned value is an empty string
    say "foo.tar.gz".IO.extension: :5parts; # OUTPUT: «␤»
# There is no 5-part extension, so we replaced nothing:
    say "foo.tar.gz".IO.extension: 'ZIP', :5parts; # OUTPUT: «"foo.tar.gz".IO␤»
# Replacing a 0-part extension is just appending:
    say "foo.tar.gz".IO.extension: 'ZIP', :0parts; # OUTPUT: «"foo.tar.gz.ZIP".IO␤»
# Replace 1-part of the extension, using '.' joiner
    say "...".IO.extension: 'tar'; # OUTPUT: «"...tar".IO␤»
# Replace 1-part of the extension, using empty string joiner
    say "...".IO.extension: 'tar', :joiner(''); # OUTPUT: «"..tar".IO␤»
# Remove 1-part extension; results in empty basename, so result is ".".IO
    say ".".IO.extension: ''; # OUTPUT: «".".IO␤»

method dirname

method dirname(IO::Path:D:)

Returns the directory name portion of the path object. That is, it returns the path excluding the volume and the base name. Unless the dirname consist of only the directory separator (i.e. it's the top directory), the trailing directory separator will not be included in the return value.

say IO::Path.new("/home/camelia/myfile.raku").dirname; # OUTPUT: «/home/camelia␤»
    say IO::Path::Win32.new("C:/home/camelia").dirname;  # OUTPUT: «/home␤»
    say IO::Path.new("/home").dirname;                   # OUTPUT: «/␤»

method volume

method volume(IO::Path:D:)

Returns the volume portion of the path object. On Unix system, this is always the empty string.

say IO::Path::Win32.new("C:\\Windows\\registry.ini").volume;    # OUTPUT: «C:␤»

method parts

method parts(IO::Path:D:)

Returns an IO::Path::Parts for the invocant.

say IO::Path::Win32.new("C:/rakudo/raku.bat").parts.raku;
    # OUTPUT: «IO::Path::Parts.new("C:","/rakudo","raku.bat")␤»

Note: Before Rakudo version 2020.06 a Map was returned, with the keys volume, dirname, basename whose values were the respective invocant parts.

method raku

method raku(IO::Path:D: --> Str:D)

Returns a string that, when given passed through EVAL gives the original invocant back.

"foo/bar".IO.raku.say;
# OUTPUT: IO::Path.new("foo/bar", :SPEC(IO::Spec::Unix), :CWD("/home/camelia"))

Note that this string includes the value of the .CWD attribute that is set to $*CWD when the path object was created, by default.

method gist

method gist(IO::Path:D: --> Str:D)

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.

say "foo/bar".IO;                       # OUTPUT: «"foo/bar".IO␤»
    say IO::Path::Win32.new: 「C:\foo/bar\」; # OUTPUT: «"C:\foo/bar\".IO␤»

method Str

method Str(IO::Path:D: --> Str)

Alias for IO::Path.path. In particular, note that default stringification of an IO::Path does NOT use the value of $.CWD attribute. To stringify while retaining full path information use .absolute or .relative methods.

method succ

method succ(IO::Path:D: --> IO::Path:D)

Returns a new IO::Path constructed from the invocant, with .basename changed by calling Str.succ on it.

"foo/file02.txt".IO.succ.say; # OUTPUT: «"foo/file03.txt".IO␤»

method open

method open(IO::Path:D: *%opts)

Opens the path as a file; the named options control the mode, and are the same as the open function accepts.

method pred

method pred(IO::Path:D: --> IO::Path:D)

Returns a new IO::Path constructed from the invocant, with .basename changed by calling Str.pred on it.

"foo/file02.txt".IO.pred.say; # OUTPUT: «"foo/file01.txt".IO␤»

method watch

method watch(IO::Path:D: --> Supply:D)

Equivalent to calling IO::Notification.watch-path with the invocant as the argument.

method is-absolute

method is-absolute(IO::Path:D: --> Bool)

Returns True if the path is an absolute path, and False otherwise.

"/foo".IO.is-absolute.say; # OUTPUT: «True␤»
    "bars".IO.is-absolute.say; # OUTPUT: «False␤»

Note that on Windows a path that starts with a slash or backslash is still considered absolute even if no volume was given, as it is absolute for that particular volume:

IO::Path::Win32.new("/foo"  ).is-absolute.say; # OUTPUT: «True␤»
    IO::Path::Win32.new("C:/foo").is-absolute.say; # OUTPUT: «True␤»
    IO::Path::Win32.new("C:foo" ).is-absolute.say; # OUTPUT: «False␤»

method is-relative

method is-relative(IO::Path:D: --> Bool)

Returns True if the path is a relative path, and False otherwise. Windows caveats for .is-absolute apply.

method absolute

multi method absolute(IO::Path:D: --> Str)
    multi method absolute(IO::Path:D: $base --> Str)

Returns a new Str object that is an absolute path. If the invocant is not already an absolute path, it is first made absolute using $base as base, if it is provided, or the .CWD attribute the object was created with if it is not.

method relative

method relative(IO::Path:D: $base = $*CWD --> Str)

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

multi method parent(IO::Path:D:)
    multi method parent(IO::Path:D: UInt:D $level)

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.

'/etc/foo'.IO.parent.say; # OUTPUT: «"/etc".IO␤»
    '/etc/..' .IO.parent.say; # OUTPUT: «"/etc".IO␤»
    '/etc/../'.IO.parent.say; # OUTPUT: «"/etc".IO␤»
    './'      .IO.parent.say; # OUTPUT: «"..".IO␤»
    'foo'     .IO.parent.say; # OUTPUT: «".".IO␤»
    '/'       .IO.parent.say; # OUTPUT: «"/".IO␤»
    IO::Path::Win32.new('C:/').parent.say; # OUTPUT: «"C:/".IO␤»

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

say "/etc/foo".IO.parent(2) eqv "/etc/foo".IO.parent.parent; # OUTPUT: «True␤»

method resolve

method resolve(IO::Path:D: :$completely --> IO::Path)

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.

# bar is a symlink pointing to "/baz"
    my $io = "foo/./bar/..".IO.resolve;      # now "/" (the parent of "/baz")

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

multi  dir(*%_)
    multi  dir(IO::Path:D $path, |c)
    multi  dir(IO()       $path, |c)
    method dir(IO::Path:D: Mu :$test = $*SPEC.curupdir)

Returns a lazy list of IO::Path objects corresponding to the entries in a directory, optionally filtered by smartmatching their names as strings per the :test parameter. The order in which the filesystem returns entries determines the order of the entries/objects in the list. Objects corresponding to special directory entries . and .. are not included. $path determines whether the objects' paths are absolute or relative.

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:

dir('mydir', test => { .IO.d })

while this will:

dir('mydir', test => { "mydir/$_".IO.d })

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 an @-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:

# To iterate over the contents of the current directory:
    for dir() -> $file {
        say $file;
    }
# As before, but include even '.' and '..' which are filtered out by
    # the default :test matcher:
    for dir(test => *) -> $file {
        say $file;
    }
# To get the names of all .jpg and .jpeg files in the home directory of the current user:
    my @jpegs = $*HOME.dir: test => /:i '.' jpe?g $/;

An example program that lists all files and directories recursively:

sub MAIN($dir = '.') {
        my @todo = $dir.IO;
        while @todo {
            for @todo.pop.dir -> $path {
                say $path.Str;
                @todo.push: $path if $path.d;
            }
        }
    }

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

my @stack = '.'.IO;
my $raku-files = gather while @stack {
    with @stack.pop {
        when :d { @stack.append: .dir }
        .take when .extension.lc eq 'raku'
    }
}
.put for $raku-files[^3];

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:

'/path/to/file'.IO ~~ :r;

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:

say :d & :x;                # OUTPUT: «all(d => True, x => True)␤»
    say '/tmp'.IO ~~ :d & :x;   # OUTPUT: «True␤»
    say '/'.IO    ~~ :d & :rw;  # OUTPUT: «False␤»

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.

You can also perform file tests on an already opened filehandle by testing against its .path method. For example, given filehandle $fh:

$fh.path ~~ :r;
$fh.path.r;       # method form

method e

method e(IO::Path:D: --> Bool:D)

Returns True if the invocant is a path that exists.

method d

method d(IO::Path:D: --> Bool:D)

Returns True if the invocant is a path that exists and is a directory. The method will fail with X::IO::DoesNotExist if the path points to a non-existent filesystem entity.

method f

method f(IO::Path:D: --> Bool:D)

Returns True if the invocant is a path that exists and is a file. The method will fail with X::IO::DoesNotExist if the path points to a non-existent filesystem entity.

method s

method s(IO::Path:D: --> Int:D)

Returns the file size in bytes. May be called on paths that are directories, in which case the reported size is dependent on the operating system. The method will fail with X::IO::DoesNotExist if the path points to a non-existent filesystem entity.

say $*EXECUTABLE.IO.s; # OUTPUT: «467␤»

method l

method l(IO::Path:D: --> Bool:D)

Returns True if the invocant is a path that exists and is a symlink. The method will fail with X::IO::DoesNotExist if the path points to a non-existent filesystem entity.

method r

method r(IO::Path:D: --> Bool:D)

Returns True if the invocant is a path that exists and is accessible. The method will fail with X::IO::DoesNotExist if the path points to a non-existent filesystem entity.

method w

method w(IO::Path:D: --> Bool:D)

Returns True if the invocant is a path that exists and is writable. The method will fail with X::IO::DoesNotExist if the path points to a non-existent filesystem entity.

method rw

method rw(IO::Path:D: --> Bool:D)

Returns True if the invocant is a path that exists and is readable and writable. The method will fail with X::IO::DoesNotExist if the path points to a non-existent filesystem entity.

method x

method x(IO::Path:D: --> Bool:D)

Returns True if the invocant is a path that exists and is executable. The method will fail with X::IO::DoesNotExist if the path points to a non-existent filesystem entity.

NOTE: If the file is a script (an executable text file and not a native executable), and the file has only executable permissions and no read permissions, this method will return True but trying to execute will fail. That is a limitation of the operating system.

method rwx

method rwx(IO::Path:D: --> Bool:D)

Returns True if the invocant is a path that exists and is executable, readable, and writable. The method will fail with X::IO::DoesNotExist if the path points to a non-existent filesystem entity.

method z

method z(IO::Path:D: --> Bool:D)

Returns True if the invocant is a path that exists and has size of 0. May be called on paths that are directories, in which case the reported file size (and thus the result of this method) is dependent on the operating system. The method will fail with X::IO::DoesNotExist if the path points to a non-existent filesystem entity.

method sibling

method sibling(IO::Path:D: Str() $sibling --> IO::Path:D)

Allows to reference a sibling file or directory. Returns a new IO::Path based on the invocant, with the .basename changed to $sibling. The $sibling is allowed to be a multi-part path fragment; see also .add.

say '.bashrc'.IO.sibling: '.bash_aliases'; # OUTPUT: «.bash_aliases".IO␤»
    say '/home/camelia/.bashrc'.IO.sibling: '.bash_aliases';
    # OUTPUT: «/home/camelia/.bash_aliases".IO␤»
say '/foo/' .IO.sibling: 'bar';  # OUTPUT: «/bar".IO␤»
    say '/foo/.'.IO.sibling: 'bar';  # OUTPUT: «/foo/bar".IO␤»

method words

method words(IO::Path:D: :$chomp = True, :$enc = 'utf8', :$nl-in = ["\x0A", "\r\n"], |c --> Seq:D)

Opens the invocant and returns its words.

The behavior is equivalent to opening the file specified by the invocant, forwarding the :$chomp, :$enc, and :$nl-in arguments to IO::Handle.open, then calling IO::Handle.words on that handle, forwarding any of the remaining arguments to that method, and returning the resultant Seq.

NOTE: words are lazily read. The handle used under the hood is not closed until the returned Seq is fully reified, and this could lead to leaking open filehandles. It is possible to avoid leaking open filehandles using the $limit argument to cut down the Seq of words to be generated.

my %dict := bag 'my-file.txt'.IO.words;
say "Most common words: ", %dict.sort(-*.value).head: 5;

method lines

method lines(IO::Path:D: :$chomp = True, :$enc = 'utf8', :$nl-in = ["\x0A", "\r\n"], |c --> Seq:D)

Opens the invocant and returns its lines.

The behavior is equivalent to opening the file specified by the invocant, forwarding the :$chomp, :$enc, and :$nl-in arguments to IO::Handle.open, then calling IO::Handle.lines on that handle, forwarding any of the remaining arguments to that method, and returning the resultant Seq.

NOTE: the lines are ready lazily and the handle used under the hood won't get closed until the returned Seq is fully reified, so ensure it is, or you'll be leaking open filehandles. (TIP: use the $limit argument)

say "The file contains ",
  '50GB-file'.IO.lines.grep(*.contains: 'Raku').elems,
  " lines that mention Raku";
# OUTPUT: «The file contains 72 lines that mention Raku␤»

routine slurp

multi method slurp(IO::Path:D: :$bin, :$enc)

Read all of the file's content and return it as either Buf, if :$bin is True, or if not, as Str decoded with :$enc encoding, which defaults to utf8. File will be closed afterwards. See &open for valid values for :$enc.

method spurt

method spurt(IO::Path:D: $data, :$enc, :$append, :$createonly)

Opens the 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.

  • :$createonlyfail if the file already exists.

method spurt(IO::Path:D:)

As of the 2020.12 release of the Rakudo compiler, it is also possible to call the spurt method without any data. This will either create an empty file, or will truncate any existing file at the given path.

method chdir

multi method chdir(IO::Path:D: IO $path, |c)
    multi method chdir(IO::Path:D: Str() $path, :$d = True, :$r, :$w, :$x)

Contrary to the name, the .chdir method does not change any directories, but merely concatenates the given $path to the invocant and returns the resultant IO::Path. Optional file tests can be performed by providing :d, :r, :w, or :x Bool named arguments; when set to True, they'll perform .d, .r, .w, and .x tests respectively. By default, only :d is set to True.

method mkdir

method mkdir(IO::Path:D: Int() $mode = 0o777 --> IO::Path:D)

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

sub    rmdir(*@dirs --> List:D)
    method rmdir(IO::Path:D: --> True)

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

method chmod(IO::Path:D: Int() $mode --> Bool)

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:

'myfile'.IO.chmod(0o444);          # make a file read-only
'somedir'.IO.chmod(0o777);         # set 0777 permissions on a directory

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

'myfile'.IO.chmod:  '0444';        # BAD!!! (interpreted as mode 0o674)
'myfile'.IO.chmod: '0o444';        # OK (an octal in a string)
'myfile'.IO.chmod:  0o444;         # Also OK (an octal literal)

routine rename

method rename(IO::Path:D: IO() $to, :$createonly = False --> Bool:D)
    sub    rename(IO() $from, IO() $to, :$createonly = False --> Bool:D)

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

method copy(IO::Path:D: IO() $to, :$createonly --> Bool:D)
    sub    copy(IO() $from, IO() $to, :$createonly --> Bool:D)

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

method move(IO::Path:D: IO() $to, :$createonly --> Bool:D)
    sub    move(IO() $from, IO() $to, :$createonly --> Bool:D)

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

method Numeric(IO::Path:D: --> Numeric:D)

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

method Int

method Int(IO::Path:D: --> Int:D)

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

method symlink(IO::Path:D $target: IO() $link, Bool :$absolute = True --> Bool:D)
    sub    symlink(      IO() $target, IO() $link, Bool :$absolute = True --> Bool:D)

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.

method link(IO::Path:D $target: IO() $link --> Bool:D)
    sub    link(      IO() $target, IO() $link --> Bool:D)

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.

method unlink(IO::Path:D: --> True)
    sub    unlink(*@filenames --> List:D)

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.

'foo.txt'.IO.open(:w).close;
'bar'.IO.mkdir;
say unlink <foo.txt  bar  not-there.txt>; # OUTPUT: «[foo.txt not-there.txt]␤»
# `bar` is not in output because it failed to delete (it's a directory)
# `not-there.txt` is present. It never existed, so that's deemed a success.

# Method form `fail`s:
say .exception.message without 'bar'.IO.unlink;
# OUTPUT: «Failed to remove the file […] illegal operation on a directory␤»

routine chown

method chown(IO::Path:D: :$uid, :$gid --> True)
    sub    chown(*@filenames, :$uid, :$gid --> List:D)

Available as of release 2022.12 of the Rakudo compiler.

Change the owner and/or group of all specified ordinary files, links, or symbolic links for which there are privileges to do so.

The subroutine form returns the names of all the files in the list, excluding those for which the filesystem raised some error.

The method form returns True on success, or fails with X::IO::Chown if the operation could not be completed.

Note that this operation only makes sense on operating systems with the concept of an "owner" and a "group", which is typically on Unix-like systems.

say "success" if 'foo.txt'.IO.chown(:uid(137));

method IO

method IO(IO::Path:D: --> IO::Path)

Returns the invocant.

method SPEC

method SPEC(IO::Path:D: --> IO::Spec)

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

my $io = IO::Path.new("/bin/bash");
    say $io.SPEC;                            # OUTPUT: «(Unix)␤»
    say $io.SPEC.dir-sep;                    # OUTPUT: «/␤»

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 created

Returns an Instant object indicating when the file was created.

say "path/to/file".IO.created;          # Instant:1424089165
say "path/to/file".IO.created.DateTime; # 2015-02-16T12:18:50Z

Available as of the 2022.12 release of the Rakudo compiler.

method modified

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

say "path/to/file".IO.modified;          # Instant:1424089165
say "path/to/file".IO.modified.DateTime; # 2015-02-16T12:18:50Z

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.

say "path/to/file".IO.accessed;          # Instant:1424353577
say "path/to/file".IO.accessed.DateTime; # 2015-02-19T13:45:42Z

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.

say "path/to/file".IO.changed;           # Instant:1424089165
say "path/to/file".IO.changed.DateTime;  # 2015-02-16T12:18:50Z

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.

say ~"path/to/file".IO.mode;  # e.g. '0644'
say +"path/to/file".IO.mode;  # e.g. 420, where sprintf('%04o', 420) eq '0644'

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

"path/to/file1".IO.chmod("path/to/file2".IO.mode);  # will change the
                                                    # permissions of file1
                                                    # to be the same as file2

Other informational methods

method user

Available as of the 2021.04 Rakudo compiler release.

The user method returns the numeric user ID (aka "uid") of the path on operating systems that support such a notion.

method group

Available as of the 2021.04 Rakudo compiler release.

The group method returns the numeric group ID (aka "gid") of the path on operating systems that support such a notion.

method dir-with-entries

Available as of the 2022.04 Rakudo compiler release.

Returns a Bool indicating whether the path is a directory with any entries in it. Throws an exception if the path is not a directory, or the path doesn't exist.

say "'$_' has entries" if .d && .dir-with-entries given "path/to/dir".IO;

method inode

Available as of the 2022.07 Rakudo compiler release.

Returns an Int object representing the inode of the path on the filesystem (if the filesystem supports such a notion).

say "path/to/file".IO.inode;  # e.g. 9003678

method dev

Available as of the 2022.07 Rakudo compiler release.

Returns an Int object representing the dev (the st_dev field of the POSIX stat function) of the path on the filesystem (if the filesystem supports such a notion).

say "path/to/file".IO.dev;  # e.g. 16777233

method devtype

Available as of the 2022.07 Rakudo compiler release.

Returns an Int object representing the devtype (the st_rdev field of the POSIX stat function) of the path on the filesystem (if the filesystem supports such a notion).

say "path/to/file".IO.devtype;  # e.g. 0

See Also

class Attribute

Member variable

class Cancellation

Removal of a task from a Scheduler before normal completion

class Channel

Thread-safe queue for sending values from producers to consumers

class CompUnit

CompUnit

class CompUnit::Repository::FileSystem

CompUnit::Repository::FileSystem

class CompUnit::Repository::Installation

CompUnit::Repository::Installation

class Distro

Distribution related information

class Grammar

Formal grammar made up of named regexes

class IO::ArgFiles

Iterate over contents of files specified on command line

class IO::CatHandle

Use multiple IO handles as if they were one

class IO::Handle

Opened file or stream

class IO::Notification

Asynchronous notification for file and directory changes

class IO::Notification::Change

Changes in a file, produced by watch-file

class IO::Path::Cygwin

IO::Path pre-loaded with IO::Spec::Cygwin

class IO::Path::Parts

IO::Path parts encapsulation

class IO::Path::QNX

IO::Path pre-loaded with IO::Spec::QNX

class IO::Path::Unix

IO::Path pre-loaded with IO::Spec::Unix

class IO::Path::Win32

IO::Path pre-loaded with IO::Spec::Win32

class IO::Pipe

Buffered inter-process string or binary stream

class IO::Socket::Async

Asynchronous socket in TCP or UDP

class IO::Socket::Async::ListenSocket

A tap for listening TCP sockets

class IO::Socket::INET

TCP Socket

class IO::Spec

Platform specific operations on file and directory paths

class IO::Spec::Cygwin

Platform specific operations on file and directory paths for Cygwin

class IO::Spec::QNX

Platform specific operations on file and directory paths QNX

class IO::Spec::Unix

Platform specific operations on file and directory paths for POSIX

class IO::Spec::Win32

Platform specific operations on file and directory paths for Windows

class IO::Special

Path to special I/O device

class Kernel

Kernel related information

class Lock

A low-level, re-entrant, mutual exclusion lock

class Lock::ConditionVariable

Condition variables used in locks

class Match

Result of a successful regex match

class Pod::Block

Block in a Pod document

class Pod::Block::Code

Verbatim code block in a Pod document

class Pod::Block::Comment

Comment in a Pod document

class Pod::Block::Declarator

Declarator block in a Pod document

class Pod::Block::Named

Named block in a Pod document

class Pod::Block::Para

Paragraph in a Pod document

class Pod::Block::Table

Table in a Pod document

class Pod::Defn

Pod definition list

class Pod::FormattingCode

Pod formatting code

class Pod::Heading

Heading in a Pod document

class Pod::Item

Item in a Pod enumeration list

class Proc

Running process (filehandle-based interface)

class Proc::Async

Running process (asynchronous interface)

class Promise

Status/result of an asynchronous computation

class Regex

String pattern

class Semaphore

Control access to shared resources by multiple threads

class Supplier

Live Supply factory

class Supplier::Preserving

Cached live Supply factory

class Supply

Asynchronous data stream with multiple subscribers

class Tap

Subscription to a Supply

class Thread

Concurrent execution of code (low-level)

class ThreadPoolScheduler

Scheduler that distributes work among a pool of threads

class Unicode

Unicode related information

class VM

Raku Virtual Machine related information

The Camelia image is copyright 2009 by Larry Wall. "Raku" is trademark of the Yet Another Society. All rights reserved.