Python Listing Folders and Reading Settings
The os module talks to the operating system. listdir() lists a folder, and environ reads settings.
List a folder you built
The program builds a folder with two files. sorted() lists their names in order.
import os
os.makedirs("demo_box", exist_ok=True)
with open(os.path.join("demo_box", "a.txt"), "w") as f:
f.write("a")
with open(os.path.join("demo_box", "b.txt"), "w") as f:
f.write("b")
print(sorted(os.listdir("demo_box")))Read a setting
The program sets APP_MODE first. get() then reads it back.
import os
os.environ["APP_MODE"] = "demo"
print(os.environ.get("APP_MODE"))A missing setting gives a fallback
NO_SUCH_SETTING is not set. get() gives back the fallback instead.
import os
print(os.environ.get("NO_SUCH_SETTING", "plain"))Example
import os
os.makedirs("settings_demo", exist_ok=True)
for name in ["notes.txt", "photo.jpg", "song.mp3"]:
path = os.path.join("settings_demo", name)
with open(path, "w") as f:
f.write("x")
print(sorted(os.listdir("settings_demo")))
print("Theme:", os.environ.get("THEME", "plain"))Key points
- Use os.listdir(folder) to list the names inside a folder
- Use sorted() on the list, because the order is not fixed
- Use os.environ.get(name) to read one setting
- Use os.environ.get(name, "fallback") when a setting may be missing
- Settings in environ hold text only, never numbers
In this example, the program builds a settings folder first. It writes three files with different endings. sorted(os.listdir()) lists their names in order. get() then reads THEME with a fallback of plain. The fallback prints because THEME is not set.
Note
listdir() lists names only. It never opens the files.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does os.listdir("photos") give back?