Python Intermediate Lesson 1: Project Folders, pathlib and Virtual Environments

Python Intermediate Lesson 1: Project Folders, pathlib and Virtual Environments 1

πŸ“Ž This article includes 3 downloadable practice files ↓

⏱ 2 min read

πŸ“˜ Python Intermediate Course Β· Lesson 1 of 10

Advertisement
In this article
  1. A project folder
  2. Virtual environment
  3. pathlib: paths that travel
  4. Common mistakes
  5. Practice

Scripts that “work on my machine” usually fail for two reasons: a missing library, or a file path that only exists on one PC. Fix both before writing more code.

A project folder

sales-report/
  .venv/              <- the virtual environment (never edit, never share)
  data/               <- input files
  output/             <- what the script creates
  report.py
  requirements.txt

Virtual environment

cd sales-report
python -m venv .venv
.venv\Scripts\activate          # Windows   (macOS/Linux: source .venv/bin/activate)
pip install pandas openpyxl
pip freeze > requirements.txt   # a colleague runs: pip install -r requirements.txt

Each project gets its own libraries and versions, so upgrading pandas for one project can’t break another.

pathlib: paths that travel

from pathlib import Path
HERE = Path(__file__).resolve().parent     # the script's own folder
data = HERE / "sales.csv"                  # / joins paths on every OS
for f in sorted((HERE / "monthly").glob("*.csv")):
    print(f.name, f.stem, f.suffix)
(HERE / "output").mkdir(exist_ok=True)
πŸ’‘ Never hard-code C:\Users\Ravi\Desktop\.... Build every path from HERE and the script works from any folder, any PC and in Task Scheduler.

Common mistakes

  • Forgetting to activate the venv: pip install goes to the global Python. Check the (.venv) prefix in the prompt.
  • Committing .venv to Git or OneDrive: share requirements.txt instead.

Practice

Unzip the practice data into a folder, put this lesson’s script in the same folder and run it (python pyi-NN.py). Compare with the expected output file. Then change one thing (a filter, a column, a format) and predict the new output before you run it.

πŸ“Ž Practice files for this article

⬇ Download all 3 files (ZIP Β· 4 KB)

  • 🐍
    Lesson 1 scriptThe complete script from this lesson, ready to run.
    ⬇ PY Β· 798 B
  • πŸ“„
    Expected outputWhat the script printed when we ran it, to compare with yours.
    ⬇ TXT Β· 295 B
  • πŸ—‚οΈ
    Practice data (zip)sales.csv (120 invoices, 2 deliberately broken rows), customers.csv, products.json, statement.txt, rates.json and 3 monthly CSVs.
    ⬇ ZIP Β· 4 KB

Free to use for learning. Files with macros (.bas) are plain text β€” import them with Alt+F11 β†’ File β†’ Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free Β· AI can be wrong

Leave a Reply

Your email address will not be published. Required fields are marked *