flowchart TD A["python pkg/mod.py"] --> B["sys.path[0] = pkg/"] B --> C["'pkg' itself is NOT importable"] C --> D["from pkg import mod -> ModuleNotFoundError"] E["python -m pkg.mod"] --> F["sys.path[0] = the current directory"] F --> G["'pkg' is importable"] G --> H["relative and absolute imports both work"] I["__name__"] --> J["'__main__' either way -- the guard behaves the same"]
Basic run
python my_script.pyUse a virtual environment
- isolate dependencies
- avoid “works on my machine”
Working directory tip
Many scripts break because they assume the current directory.
Prefer pathlib.Path(__file__):
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
print(BASE_DIR)🧪 Try It Yourself
Exercise 1 – List Files with os.listdir
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Output
Press Run to see what your code prints.Exercise 2 – Join Paths with os.path.join
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Output
Press Run to see what your code prints.Exercise 3 – Write and Read a File
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Output
Press Run to see what your code prints.