← Back to Python Course | Chapter 12: Standard Library | Lesson 1 of 9

Python os Module

Getting Working Directory

The os module is the main interface between your script and the underlying operating system. os.getcwd() returns the absolute path of the directory your program was launched from or has since changed into, which is often the reference point for building other relative paths.

Example: Getting Working Directory

python
import os
print(os.getcwd())

Creating and Deleting Folders

os.mkdir() creates a single new directory and fails if any parent directory in the path doesn't already exist, while os.makedirs() creates the entire chain of intermediate directories needed. os.rmdir() only removes a directory if it's completely empty, refusing to delete anything that still contains files.

Example: Creating and Deleting Folders

python
import os

os.makedirs("demo_dir/sub", exist_ok=True)
os.rmdir("demo_dir/sub")
print("Folder created and removed")

Listing Directory Contents

os.listdir(path) returns the names of every file and subdirectory directly inside the given folder, as a plain list of strings with no distinction between the two kinds of entries. You typically pair it with os.path.isfile() or os.path.isdir() afterward if you need to tell files and folders apart.

Example: Listing Directory Contents

python
import os
print(os.listdir("."))

Joining and Splitting Paths

Building file paths with plain string concatenation breaks across operating systems because Windows uses backslashes while Unix-like systems use forward slashes. os.path.join() inserts the correct separator for whatever platform the code is running on, so the same code produces valid paths everywhere.

Example: Joining and Splitting Paths

python
import os
path = os.path.join("folder", "file.txt")
print(path)

Checking File Existence

os.path.exists() checks whether anything -- file or directory -- exists at a given path, returning False rather than raising an error if it doesn't. os.path.isfile() and os.path.isdir() narrow that check further, letting you confirm not just that a path exists but which kind of thing it actually is.

Example: Checking File Existence

python
import os
print(os.path.exists("."))
print(os.path.isdir("."))

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.