Course of Raku / Objects, I/O, and exceptions / Input and output

Working with directories

To work with the file system itself — checking what exists and creating directories — Raku uses path objects. Any string can be turned into one with the .IO method, and the path object then answers questions about that path.

The most common questions are whether a path exists, and what kind of thing it is:

spurt 'greeting.txt', 'hi';

say 'greeting.txt'.IO.e; # True  — does it exist?
say 'greeting.txt'.IO.f; # True  — is it a file?
say 'greeting.txt'.IO.d; # False — is it a directory?

.e tests existence, .f tests for a regular file, and .d tests for a directory.

To create a new directory, use mkdir:

mkdir 'reports';
say 'reports'.IO.d; # True

The next topic shows how to list what a directory contains.

Also in this section

Practice

Complete the quiz that covers the contents of this section.

Exercises

This section contains 3 exercises. Examine all the topics of this section before doing the coding practice.

  1. Does it exist?
  2. Make a directory
  3. File or directory?

Course navigation

Solution: Count the characters   |   Listing a directory