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

File handles

Reading or writing a whole file at once is convenient, but sometimes you want to go through a file one line at a time, or keep a file open while you write to it repeatedly. For that you use a file handle.

The simplest way to read a file line by line does not even need an explicit handle: the lines method on a path object gives the lines one at a time, ready for a for loop:

spurt 'words.txt', "one\ntwo\nthree\n";

for 'words.txt'.IO.lines -> $line {
    say $line.uc;
}

Each $line is a single line, without its trailing newline. The program prints:

ONE
TWO
THREE

To write to a file through a handle, open it with open and the :w (write) flag, use the handle’s say or print methods, and close it when done:

my $fh = open 'out.txt', :w;
$fh.say('first line');
$fh.say('second line');
$fh.close;

Closing the handle makes sure everything you wrote is flushed to disk. Reading line by line, as above, is the usual way to handle files that are too large to slurp into memory all at once.

Practice

Complete the quiz that covers the contents of this topic.

Exercises

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

  1. Number the lines
  2. Count the lines
  3. Write with a handle
  4. Pass a handle to a function

Course navigation

Quiz — Deleting files   |   Number the lines