The os Module - Navigating Directories
What osos is for
The osos module provides:
- current working directory
- directory listing
- environment variables
- basic path manipulation (but prefer
pathlibpathlibfor paths)
Current working directory
cwd.py
import os
print(os.getcwd())cwd.py
import os
print(os.getcwd())List files
listdir.py
import os
for name in os.listdir("."):
print(name)listdir.py
import os
for name in os.listdir("."):
print(name)Change directory
chdir.py
import os
os.chdir("/tmp")
print(os.getcwd())chdir.py
import os
os.chdir("/tmp")
print(os.getcwd())Environment variables
env_vars.py
import os
print(os.environ.get("HOME"))env_vars.py
import os
print(os.environ.get("HOME"))Notes
For paths, use pathlib.Pathpathlib.Path whenever possible.
๐งช Try It Yourself
Exercise 1 โ List Files with os.listdir
Exercise 2 โ Join Paths with os.path.join
Exercise 3 โ Write and Read a File
If this helped you, consider buying me a coffee โ
Buy me a coffeeWas this page helpful?
Let us know how we did
