Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Files, Paths and Text I/O

The os module

Reference for Python's os module: environment variables, listing and creating directories, renaming and removing files, os.walk, scandir and os.name.

The os module is Python's gateway to the operating system: environment variables, the current directory, directories and files, process information. Many functions mirror classic operating-system calls, so they work with plain strings.

For path manipulation and everyday file work, pathlib is usually more pleasant. os remains important for environment variables, os.walk(), os.scandir(), permissions and low-level calls. Which functions exist and what they do can differ between Windows, Linux and macOS.

Python
import os

print(os.environ.get("HOME"))
print(os.listdir("."))

Try it

Python Working with folders and files

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Environment variables, errors and platform facts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Most useful functions

Function Description
os.getcwd(), os.chdir(path) Get or change the current working directory.
os.listdir(path=".") Names in a directory, as a list in arbitrary order.
os.scandir(path=".") Iterator of DirEntry objects with cached is_dir(), is_file(), stat(); use it as a context manager.
os.walk(top) Yields (folder, subfolders, files) for each directory in a tree. Edit subfolders in place to prune or order the walk.
os.mkdir(path), os.makedirs(path, exist_ok=False) Create one directory, or all missing levels.
os.rmdir(path), os.removedirs(path) Remove empty directories.
os.remove(path) / os.unlink(path) Delete a file.
os.rename(src, dst), os.replace(src, dst) Rename or move; replace overwrites an existing target on every platform.
os.stat(path) Size, modification time and mode in a stat_result.
os.environ, os.getenv(name, default=None), os.putenv() Environment variables (a mapping of str to str). Prefer os.environ for setting values.
os.getpid(), os.cpu_count() Process id, number of CPUs (or None).
os.sep, os.linesep, os.pathsep, os.name Path separator, line ending, PATH separator, "posix" or "nt".
os.system(cmd) Runs a shell command. Prefer subprocess.run().

Raises: subclasses of OSError such as FileNotFoundError, FileExistsError, NotADirectoryError, IsADirectoryError, PermissionError; TypeError for non-string environment values.

Usage notes

  • Order is not guaranteed. listdir(), scandir() and walk() return entries in whatever order the file system gives them; use sorted() for stable output.
  • Environment changes are local. Assigning to os.environ changes the current process and child processes, never your shell or other programs.
  • os.getenv() returns None for missing names (or your default), while os.environ["NAME"] raises KeyError.
  • Deleting is permanent. os.remove() does not use a recycle bin. os.rmdir() only removes empty folders; use shutil.rmtree() for whole trees.
  • os.walk() follows no symlinks by default (followlinks=False) and by default ignores errors while listing; pass onerror to see them.
  • Never build shell commands from user input with os.system(); it invites injection.
  • Portability. Use os.path.join() or pathlib instead of hard-coded / or \. Some functions (os.getuid(), os.fork()) exist only on Unix.
  • Time-of-check races. if os.path.exists(p): os.remove(p) can fail if the file disappears in between; catching FileNotFoundError is more reliable.
  • In this page's live examples the file system lives in memory for a single run; on your computer the same code works on real files.