Exercises
os and sys
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Read a setting from the environment, falling back to a default.
Python
import os
os.environ["APP_MODE"] = "demo"
# print APP_MODE, then a missing one with the default "unset"
os.environ behaves like a dictionary.
import os
os.environ["APP_MODE"] = "demo"
print(os.environ.get("APP_MODE"))
print(os.environ.get("NOT_THERE", "unset"))Exercise 2Passed
Create the nested folder without failing when it already exists, then confirm it.
Python
import os
# make data/reports twice, then print whether it is a directory
makedirs takes exist_ok.
import os
os.makedirs("data/reports", exist_ok=True)
os.makedirs("data/reports", exist_ok=True)
print(os.path.isdir("data/reports"))Exercise 3Passed
Split the filename into its stem and extension.
Python
import os
name = "march.csv"
# print ('march', '.csv')
os.path has a function for exactly this.
import os
name = "march.csv"
print(os.path.splitext(name))