Lecture 19

The os module

MCS 260 Fall 2021
Emily Dumas

Reminders

  • Project 2 due Friday at 6:00pm central
  • Worksheet 7 available
    • Thursday lab students: attempt problem 1

    Current working directory

    The OS keeps track of a current working directory (CWD) for every program.

    The terminal usually shows the CWD in the prompt.

    When you run a program in the terminal, it inherits the terminal's CWD.

    open("foo.txt","r") looks for foo.txt in the CWD.

    CWD recommendation

    Always run your Python scripts from the terminal, first changing directory to the one containing the script.

    Running a script when your terminal is in a different directory can have confusing results.

    . and ..

    Context-dependent special directory names:

    • . refers to the current directory
    • .. refers to the parent directory

    The os module

    
            import os
        

    gives your program access to lots of functions that ask the operating system to do things.

    Today we focus on the filesystem operations in this module.

    Shell commands

    • pwd - print working directory
    • cd - change working directory
    • ls - list files in a directory
    • rm - remove a file
    • mkdir - create a directory
    • rmdir - remove a directory
    • cat - display file contents

    os module functions

    • os.getcwd() - get current working directory
    • os.chdir(x) - change working directory to x
    • os.listdir(x) - get list of files in dir x
    • os.remove(fn) - delete a file (skip recycling bin)
    • os.mkdir(x) - create directory x
    • os.rmdir(x) - remove directory x (must be empty)

    os module functions

    • os.path.join(part0,part1,...) - join path components (using proper separator for the OS)
    • os.path.exists(name) - True if name exists
    • os.path.isfile(name) - True if name is a file
    • os.path.isdir(name) - True if name is a directory

    Goodies skipped for now

    os.path.dirname - All but the last component of a path (i.e. the directory part, if the path includes a filename)

    • e.g. On Windows, os.path.dirname("C:\\Users\\dd\\out.txt") returns "C:\\Users\\dd"

    os.path.basename - The last component of a path (i.e. the filename part, if the path includes one)

    • e.g. On Windows, os.path.dirname("C:\\Users\\dd\\out.txt") returns "out.txt"

    Let's write our own mini-terminal

    References

    Revision history

    • 2021-10-05 Initial publication