MCS 260 Fall 2021
Emily Dumas
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.
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.
Context-dependent special directory names:
.
refers to the current directory..
refers to the parent directory
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.
pwd
- print working directorycd
- change working directoryls
- list files in a directoryrm
- remove a filemkdir
- create a directoryrmdir
- remove a directorycat
- display file contentsos.getcwd()
- get current working directoryos.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.path.join(part0,part1,...)
- join path components (using proper separator for the OS)os.path.exists(name)
- True if name
existsos.path.isfile(name)
- True if name
is a fileos.path.isdir(name)
- True if name
is a directoryos.path.dirname
- All but the last component of a path (i.e. the directory part, if the path includes a filename)
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)
os.path.dirname("C:\\Users\\dd\\out.txt")
returns "out.txt"
Let's write our own mini-terminal