Chapter 15

The os Module

On this page

Picat has an os module for manipulating files and directories. In order to use any of the functions or predicates, users must import the module.

15.1 The Path Parameter

Many of the functions and predicates in this module have a Path parameter. This parameter is a string or an atom, representing the path of a file or directory. This path can be an absolute path, from the system’s root directory, or a path relative to the current working directory. Different systems use different separator characters to separate directories at different levels of the directory hierarchy. For example, Windows uses ‘∖’ and Unix uses ‘/’. The following function outputs a single character, representing the character that the current system uses as a file separator.

15.2 Directories

The os module includes functions for reading and modifying directories. The following example shows how to list all of the files in a directory tree, using a depth-first directory traversal.

Example

import os.

traverse(Dir), directory(Dir) =>
   List = listdir(Dir),
   printf("Inside %s%n", Dir),
   foreach (File in List)
       printf("    %s%n", File)
   end,
   foreach (File in List, File != ".", File != "..")
       FullName = Dir ++ [separator()] ++ File,
       traverse(FullName) 
   end.
traverse(_Dir) => true.

The following function can be used to read the contents of a directory:

The above example also uses the directory predicate, which will be discussed in Section 15.4.

15.2.1 The Current Working Directory

The os module includes built-ins for obtaining the program’s current working directory, inspecting files in the directory, and changing the directory.

15.3 Modifying Files and Directories

15.3.1 Creation

The os module contains a number of predicates for creating new files and directories:

15.3.2 Deletion

The os module contains a number of predicates for deleting files and directories.

15.4 Obtaining Information about Files

The os module contains a number of functions that retrieve file status information, and predicates that test the type of a file. Unless specified otherwise, these predicates will all throw an error if the program does not have permission to read from Path.

The following example shows how to use a few of the predicates.

Example

import os.

test_file(Path) =>
    if (not exists(Path))
        printf("%s does not exist %n", Path)
    elseif (directory(Path))
        println("Directory")
    elseif (file(Path))
        println("File")
    else
        println("Unknown")
    end.

15.5 Environment Variables