← Cookbook Files and processes Beginner · Pooka 0.5.0

List a directory

Look inside a folder, keep the files with the extension you care about, and print their names in order.

You will use

  • pooka/file: list_directory, create_directories, remove_directory
  • pooka/path: path.join, path.extension, path.stem

The whole program

src/main.pooka
module main

import pooka/file.{FileError}
import pooka/io
import pooka/list
import pooka/path
import pooka/string

/// Every file in `folder` with the given extension, sorted by name.
files_with(folder: String, wanted: String) -> Result(List(String), FileError) {
  let names = file.list_directory(folder)?
  Ok(
    names
    |> list.filter(fn(name: String) { path.extension(name) == Some(wanted) })
    |> list.sort_by(string.compare)
  )
}

main() {
  // A small shelf to look at.
  let _ = file.create_directories("shelf")
  loop name in ["moon.txt", "owl.txt", "lamp.png", "attic.txt"] {
    let _ = file.write(path.join(["shelf", name]), "")
  }

  match files_with("shelf", ".txt") {
    Ok(names) -> list.each(names, fn(name: String) {
      io.println(path.stem(name))
      Nil
    })
    Error(problem) -> {
      io.eprintln(problem.message)
      Nil
    }
  }

  loop name in ["moon.txt", "owl.txt", "lamp.png", "attic.txt"] {
    let _ = file.delete(path.join(["shelf", name]))
  }
  let _ = file.remove_directory("shelf")
}

Run it

The program makes a small shelf folder, lists it, and removes it again:

$ pooka run
attic
moon
owl

How it works

  1. Names, not paths. file.list_directory("shelf") returns the names inside the folder, like "owl.txt", in no particular order. Use path.join to turn a name back into a path.
  2. Extensions keep their dot. path.extension("owl.txt") is Some(".txt"), and a name without one gives None. Comparing with Some(wanted) handles both.
  3. Sort before showing. list.sort_by(string.compare) puts the names in alphabetical order, and path.stem drops the extension for display.
  4. One ?, one Result. files_with returns Result(List(String), FileError), so a missing folder is a message, not a crash.

Try next: use file.is_directory to walk into subfolders, calling your function again for each one.