Python os Module
In this page:
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
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
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
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
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
import os
print(os.path.exists("."))
print(os.path.isdir("."))
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: