4 - Modules, File I/O, and Error Handling — Topics & Learning Outcomes
Module Topics
Introduction to Python Modules
Explains what modules are, why they are used, and how Python locates and loads them at runtime.
- What Is a Module? — A module is a single Python file containing definitions, functions, classes, and variables that can be reused in other scripts.
- Importing Modules with import — The import statement loads a module into the current namespace, making its contents accessible via dot notation.
- Selective Imports with from…import — The from…import syntax lets you import specific names from a module directly into the current namespace.
- Module Aliases — The 'as' keyword creates a shorter or more descriptive alias for an imported module or name.
- The Module Search Path — When Python encounters an import statement it searches a sequence of directories defined in sys.path to locate the module file.
Writing and Using Custom Modules
Covers how to design, write, and import your own Python modules to share reusable engineering functions across projects.
- Creating a Custom Module File — A custom module is created by writing functions, classes, or constants in a .py file and saving it in a location accessible to your scripts.
- The __name__ == '__main__' Guard — This guard allows a module file to contain both reusable code and a standalone test or demo block that only executes when the file is run directly.
- Organizing Functions and Constants — Group related functions and constants logically within a module to make the interface clear to other developers and scripts.
- Importing Your Custom Module — Once saved in the correct directory, a custom module is imported using the same syntax as any standard library module.
- Documenting a Custom Module — Good documentation within a module enables other engineers to understand and correctly use its functions without reading the implementation.
Using Standard Library Modules
Introduces key modules included with Python that are immediately useful for engineering scripting tasks without additional installation.
- The math Module — The math module provides mathematical functions and constants commonly needed in engineering calculations.
- The os and os.path Modules — The os module provides operating-system-independent functions for interacting with the file system and environment.
- The sys Module — The sys module exposes interpreter-level variables and functions, including command-line arguments and the module search path.
- The datetime Module — The datetime module supplies classes for manipulating dates and times, which is useful for timestamping engineering data logs.
- The random Module — The random module generates pseudo-random numbers and provides tools for random sampling, useful in simulations and testing.
File I/O with the with Statement
Explains how to open, read, and write text files safely using Python's with-statement context manager to guarantee proper resource cleanup.
- Opening Files and File Modes — Python's built-in open() function returns a file object that provides methods for reading and writing; the mode argument determines how the file is accessed.
- The with Statement Context Manager — The with statement ensures a file is automatically closed when the indented block exits, even if an exception occurs.
- Reading Text Files — File objects provide multiple methods for reading text content depending on whether you need the entire file, one line, or all lines as a list.
- Writing Text Files — Opening a file in write or append mode allows you to output strings to the file using the write or writelines methods.
- Working with File Paths Using pathlib — The pathlib module provides an object-oriented interface for constructing and manipulating file paths that works consistently across operating systems.
Reading and Writing CSV Files
Covers using Python's built-in csv module to read tabular data from CSV files and write structured results, a common task in engineering data workflows.
- What Is a CSV File? — A CSV (Comma-Separated Values) file stores tabular data as plain text, with each row on a new line and columns separated by a delimiter, typically a comma.
- Reading CSV Files with csv.reader — csv.reader wraps a file object and returns an iterator that yields each row as a list of strings.
- Reading CSV Files with csv.DictReader — csv.DictReader reads each row as an ordered dictionary, using the header row as keys, which makes column access by name more readable.
- Writing CSV Files with csv.writer — csv.writer provides methods to write rows to a CSV file, handling quoting and delimiter escaping automatically.
- Writing CSV Files with csv.DictWriter — csv.DictWriter writes dictionaries as CSV rows, with field names specified at construction time.
Working with JSON
Introduces JSON as a human-readable data interchange format and demonstrates how Python's json module serializes and deserializes data for configuration files and APIs.
- What Is JSON? — JSON (JavaScript Object Notation) is a lightweight, text-based format for representing structured data using key-value pairs, arrays, and nested objects.
- Parsing JSON with json.loads and json.load — Python's json module converts a JSON string or file into native Python data structures using the loads and load functions.
- Serializing Data with json.dumps and json.dump — The json module converts Python objects into JSON-formatted strings or writes them to a file using dumps and dump.
- JSON for Configuration Files — Storing simulation parameters or tool settings in a JSON file allows engineers to modify inputs without editing source code.
- Limitations of Python's json Module — Not all Python objects can be directly serialized to JSON; certain types require custom handling or conversion before they can be encoded.
Error Handling with try-except
Explains Python's exception handling model and demonstrates how to use try-except blocks to build resilient engineering scripts that recover gracefully from runtime errors.
- What Is an Exception? — An exception is a runtime error that interrupts normal program flow; if not handled, it terminates the script and displays a traceback.
- Basic try-except Structure — A try block contains code that might raise an exception; the except block defines how to respond if a specific exception type is raised.
- The else and finally Clauses — The optional else clause runs only if no exception was raised; the finally clause runs unconditionally and is used for cleanup actions.
- Accessing Exception Information — Using 'as' in an except clause binds the exception object to a variable, providing access to its message and attributes for logging or debugging.
- Raising Exceptions — The raise statement lets you deliberately trigger an exception when your code detects an invalid condition, signaling errors clearly to calling code.
- Practical Error Handling in Engineering Scripts — Combining try-except with file I/O, user input, and numeric operations produces robust scripts that handle real-world data quality issues gracefully.
Student Learning Outcomes
By the end of this module, students will be able to:
MO1
Construct a custom Python module containing reusable engineering functions, organized with a __name__ == '__main__' guard and module-level documentation
Level: CreateType: CognitiveCourse mapping: CO2
MO2
Apply the with-statement context manager to read from and write to text and CSV files using Python's built-in open() function and csv module
Level: ApplyType: CognitiveCourse mapping: CO3
MO3
Serialize and deserialize structured engineering data between Python objects and JSON format using the json module's load, loads, dump, and dumps functions
Level: ApplyType: CognitiveCourse mapping: CO1
MO4
Implement try-except blocks with else, finally, and raise clauses to handle runtime exceptions in scripts that perform file I/O and numeric operations
Level: ApplyType: CognitiveCourse mapping: CO3
MO5
Select appropriate standard library modules — including math, os, datetime, and pathlib — to accomplish specified engineering scripting tasks
Level: AnalyzeType: CognitiveCourse mapping: CO3
Course Outcomes (reference)
CO1Use variables, arrays and object structures appropriate to solve engineering problems.
CO2Write computer functions to meet specific calculation needs.
CO3Write computer programs to solve mathematical expressions and engineering problems