Files, modules and errors
Reading and writing files, modules, packages and error handling.
Level 201 · 19 lessons · 21 practice labs
Lessons
Scripts and the file system
- The REPL and executable scripts: You learn to try Python in the interactive shell (REPL) and to turn your code into a script file that can be run directly.
- File and folder work with os and shutil: You learn to create, copy, move and delete files and folders from a script using the os and shutil modules.
- Walking a directory tree with pathlib
- Reading, changing and saving JSON: You learn to read settings from a JSON file, change them, save them back, and notice when a file is broken.
- Writes that never half-finish: temp file and rename
- Short task: a script that archives old files
Modules and packages
- Where Python looks for modules: sys.path
- Packages, __init__.py and relative imports
- Running commands and capturing output with subprocess: You learn to run a system command from Python and capture its output and failure status safely.
- Network and service checks with urllib: You learn to write a simple network and service check that sends a request with urllib and inspects the response code.
- Short task: turn your helper functions into a package
Errors and safe input
- Error handling: You learn to make a program catch an unexpected error and carry on with a clear message instead of crashing.
- Custom exception classes and exception chaining: You define your own error types and re-raise errors without losing the original cause, so failures explain themselves.
- Step-by-step debugging with pdb: You run code line by line in pdb, set breakpoints and watch variable values to locate where a bug starts.
- Input validation: checking untrusted data before you use it: You write functions that check data from users and files for type, length and allowed values before it is used.
- Running commands safely: avoiding shell=True: You keep outside values from altering a command by passing an argument list instead of a shell string.
- Loading data safely: the pickle risk and yaml.safe_load: You avoid formats that can run code when loading untrusted files and choose safe paths such as JSON and safe_load.
- Short task: a loader that survives a broken config file
Capstone
- Capstone: a system health-check script: In a fictional company you write a small health-check script that checks disk, memory and service status and prints a summary.
Practice labs
- Validating a quantity field against a range: Write a function that converts a text quantity to an integer, checks the 1-99 range and raises a ValueError naming the field on failure.
- Collecting every error in a nested order: Validate nested order data without stopping at the first error, collecting all of them with paths like 'items[2].qty' in a single exception.
- Finding files by extension: Write a function that uses pathlib to find the .log files in a folder tree and return them with their sizes, largest first.
- Tidying a downloads folder: Complete a script that moves files into subfolders by extension with shutil and pathlib without overwriting files of the same name.
- Measuring folder size without symlink loops: Write a function that totals the size of a tree containing symbolic links and permission errors without looping or crashing.
- Updating a field in a JSON file: Write a function that changes one field in a JSON file of user records and saves it back with indentation.
- Saving a settings file without half-writes: Write a function that saves settings through a temporary file and os.replace; the tests check the old file survives even if writing fails halfway.
- Merging a JSON inventory with a backup: Write a function that backs up before merging two JSON inventories, rolls back on broken JSON and writes the result atomically.
- Choosing what a package exports: Gather scattered helper modules behind one package interface with __init__.py and __all__; the tests check that only the documented names are exported.
- Fixing a relative import error: Make a module inside a package that raises ImportError when run directly work with relative imports and python -m.
- Finding a shadowed module name: Find and fix an import broken by a json.py file in the project by examining the sys.path order; the tests check the right module is loaded.
- Capturing command output: Write a function that captures df output with subprocess.run and returns the mount point with the highest usage percentage.
- Checking a local service's health endpoint: Write a function that sends a request with a timeout to a local service in the lab using urllib, reports status and response time, and does not crash on connection errors.
- Running a command with user input, without a shell: Make a tool that takes a host name from the user and runs ping with shell=True safe by switching to an argument list and validating the input.
- Writing a custom exception for orders: Define an exception class that carries the product code and missing quantity when stock runs short, and use it in the order function.
- Adding context by chaining exceptions: Write a loader that wraps a lower-level ValueError in your own ConfigError with raise from; the tests check the original cause is kept.
- Validating sign-up form data: Write a validator that checks name, age and e-mail fields for type, range and format and returns all errors at once.
- Closing an unsafe YAML load: Switch an import module that reads outside data with yaml.load and pickle to yaml.safe_load and JSON; the tests check that inputs trying to build objects are rejected.
- Deciding on retries with exception classes: Build a small exception hierarchy for an import tool that separates temporary from permanent errors; only temporary errors are retried up to three times and the original cause stays in the chain.
- Reading INI settings with the right types: Convert the port value to an integer and the debug flag to a boolean in a settings file read with configparser, using defaults for missing keys.
- Checking required fields in loaded settings: Write a function that checks required keys and their types in a settings dictionary loaded from a file, listing every missing or wrongly typed field in a single error message.
About this course
Reading and writing files, modules, packages and error handling.
What you will learn
- Scripts and the file system
- Modules and packages
- Errors and safe input
- Capstone
Prerequisites
Finishing the level 101 courses of the same path, or knowing those topics, is enough.
Lab environment
Lessons run in your own Kali Linux terminal that opens in the browser. Nothing to install; the lab starts clean in every lesson.
Frequently asked questions
- Is this course right for my level?
- The course is at level 201; it assumes you know the topics of the lower-level courses.
- Is there anything to install?
- No. Every lesson runs in your own lab environment that opens in the browser.
- How do lessons work?
- Each lesson has 8 to 10 steps and a short quiz. Early steps show the command to type, later steps give less help; if two attempts fail, the solution opens.
- Can I try it for free?
- Yes. The first three lessons of every course are free.