Python os Module
In this page:
import os
os.getcwd()
os.listdir(path)
os.path.join(part1, part2)
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) # creates every intermediate directory needed
os.rmdir("demo_dir/sub") # only works because the directory is empty
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") # inserts the correct separator for the current OS
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(".")) # True whether it's a file or a directory
print(os.path.isdir(".")) # confirms it's specifically a directory
- Building paths with string concatenation such as
"folder" + "/" + "file"instead ofos.path.join(), which breaks across operating systems. - Calling
os.mkdir()on a folder that already exists, which raisesFileExistsError; useos.makedirs(path, exist_ok=True). - Using
os.remove()on a directory, which fails; useos.rmdir()orshutil.rmtree().
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: