
Every dependable automation script starts with an isolated, predictable environment. If your scripts rely on whatever packages happen to be installed on your computer, they will break the moment you move them to another machine or a server. In this opening lecture you will create a virtual environment and check it from inside Python.
You will begin with the problem a virtual environment solves. Different projects need different versions of the same libraries, and installing everything globally leads to conflicts that are hard to untangle. A virtual environment gives each project its own private folder of packages.
Next you will create one with the standard venv module, using the command for your operating system, and activate it in your terminal. You will see how the prompt changes and how the python and pip commands now point inside the environment. You will install a small package, list what is installed and compare the result with the global setup.
Then you will write a short Python script that checks the environment from the inside. It will print the interpreter path, compare sys.prefix with sys.base_prefix to decide whether a virtual environment is active and report the Python version. A check like this is useful at the start of any automation job, because it fails early with a clear message.
You will also learn how to record dependencies in a requirements file and recreate the environment from it.
By the end of this lecture you will be able to create and activate a virtual environment, verify it from Python and keep a project's dependencies reproducible.
Automation scripts are rarely run only by their author. They are launched from terminals, schedulers and other programs, and they need a clear, consistent way to receive instructions. In this lecture you will write your first command-line script with argparse, the standard library tool for the job.
You will begin by looking at what a command-line interface looks like from the outside. A user types the script name followed by arguments, and expects helpful behaviour when something is wrong or when they ask for help. You will see why reading sys.argv by hand quickly becomes messy and error-prone.
Next you will create an ArgumentParser with a description, and add a positional argument, such as the name of a folder to process. You will call parse_args and read the values from the resulting namespace. You will run the script with correct input, with no input and with the help flag, and read the messages that argparse produces for you automatically, including the usage line and error text.
You will learn how to set the type of an argument so that numbers are converted for you and invalid values are rejected before your code runs. You will also put the logic in a main function and use the standard main guard, so that the script can be imported for testing later.
By the end of this lecture you will be able to build a simple command-line tool, read positional arguments and rely on argparse for help and error messages.
A useful tool lets people adjust its behaviour without editing the code. Optional flags and sensible defaults make a script flexible while keeping the common case simple. In this lecture you will add flags and defaults to your command-line interface.
You will begin with the two main kinds of arguments. Positional arguments are required and identified by their order, while optional arguments start with dashes and can be given in any order. You will add options such as an output folder, a number of repeats and a verbosity setting, each with a long name and a short alias.
Next you will explore the features that make flags practical. You will set default values so that the script works when an option is left out, use the choices parameter to limit a value to an approved list and write clear help text for every option. You will add boolean switches with the store_true action, such as a dry-run flag, which you will use often in later lectures to preview what a script would do without changing anything.
You will test the script with different combinations, including invalid values, and read how argparse reports them. You will also see how the dest and metavar settings affect the names in the help output.
You will finish by organising the parser into a function, so that its construction is easy to read and test.
By the end of this lecture you will be able to add optional arguments, defaults, choices and boolean switches to a command-line tool.
Command-line flags are fine for a few settings, but real automation tasks have many, such as folders, file patterns and thresholds. Typing them every time is tedious and easy to get wrong. In this lecture you will load settings from a JSON configuration file.
You will begin by designing the file. JSON is a good choice because it is simple, readable and supported by the standard library. You will create a small file with keys for an input folder, an output folder, a list of file extensions and a retention period, and discuss how to name keys clearly.
Next you will write a function that reads the file with the json module. You will open it with a context manager, parse it with json.load and return a dictionary. You will handle the problems that occur in practice: the file does not exist, the file is not valid JSON or a required key is missing. For each one, you will raise or print an error that tells the user what to fix, including the file name and, for syntax errors, the line number that json reports.
You will add a set of built-in defaults, so that a configuration file only needs to list the values it wants to change. You will also validate types, for example making sure that a list of extensions really is a list.
You will test with a valid file and several broken ones.
By the end of this lecture you will be able to load, validate and default configuration from JSON in a reliable way.
You now have two ways to supply settings, a configuration file and command-line arguments. A well-designed tool lets them work together, so that the file provides everyday defaults and the command line can override them for a single run. In this lecture you will merge command-line arguments over configuration defaults.
You will begin by defining the order of precedence. The usual rule is that built-in defaults are overridden by the configuration file, which is overridden by command-line arguments. This is predictable and easy to explain to users.
Next you will notice a subtle problem. If argparse gives every option a default, you cannot tell whether the user supplied a value or the parser filled it in. You will solve it by setting the argparse defaults to None, so that only values that were actually provided are treated as overrides.
You will write a merge function that starts from the defaults, updates them with the configuration file values and then applies each command-line value that is not None. You will keep the function pure, returning a new dictionary rather than changing the inputs, which makes it easy to test.
You will also add a small report that shows where each final value came from, which is very helpful when a script behaves unexpectedly.
You will test every combination, including a flag that is set to false deliberately and a config value that is overridden.
By the end of this lecture you will be able to combine layered settings with a clear order of precedence and explain the source of each value.
Print statements are fine for quick experiments, but an automation script that runs unattended needs better records. When a job fails at three in the morning, you need to know what happened, when and how serious it was. In this lecture you will replace print with the logging module.
You will begin with the limits of print. It has no levels, no timestamps and no easy way to send messages to a file or turn them off. The logging module adds all of these, with very little extra code.
Next you will learn the standard levels from debug up to critical and decide what belongs at each. You will create a logger with getLogger, configure it with basicConfig and set a format that includes the time, the level, the logger name and the message. You will replace the print calls in your script with calls such as logger.info and logger.error.
You will add a file handler so that messages are written to a log file as well as the console, and use different levels for each destination. You will connect the verbosity flag you created earlier so that a user can request debug output. You will also log exceptions with logger.exception, which records the full traceback, and learn why you should pass values as arguments instead of formatting the string yourself.
You will take care never to write passwords or tokens to a log.
By the end of this lecture you will be able to set up logging with levels, formats and handlers, and use it throughout your automation scripts.
File handling is the bread and butter of automation, and Python has a modern tool for it: the pathlib module. Instead of treating paths as plain strings and gluing them together, pathlib represents them as objects with useful methods. In this lecture you will navigate the file system with pathlib.
You will begin by creating Path objects. You will see how the slash operator joins parts of a path in a way that works on every operating system, which removes the old problem of separators and string concatenation. You will find the current directory, the home directory and the location of the script itself.
Next you will inspect a path. You will use properties such as name, stem, suffix, parent and parts to take paths apart, and methods such as exists, is_file and is_dir to ask what is there. You will use resolve to get an absolute path and relative_to to express one path in terms of another.
Then you will explore folders. You will list the contents with iterdir, find files by pattern with glob, search subfolders with rglob and sort the results. You will build a short script that walks a practice folder and prints a tidy summary of the files by extension.
You will also learn to create directories with mkdir, using parents and exist_ok to avoid errors.
By the end of this lecture you will be able to build paths portably, take them apart and search folders with pathlib.
Reading and writing files looks simple, but automation scripts must be careful. A crash halfway through a write can leave a damaged file, and a missing folder can stop a job. In this lecture you will read and write files safely with pathlib.
You will begin with the convenient methods that pathlib provides. read_text and write_text handle opening and closing for you, and read_bytes and write_bytes do the same for binary data. You will specify the encoding explicitly, usually UTF-8, because relying on the system default is a common source of bugs when scripts move between machines.
Next you will learn the safe write pattern. Instead of writing straight to the final file, you will write to a temporary file in the same folder and then replace the original with it using the replace method. Because the replacement is a single step, other programs see either the old complete file or the new complete file, never a half-written one.
You will also create parent folders before writing, check that a file exists before reading and handle the exceptions that can occur, such as FileNotFoundError and PermissionError, with helpful messages.
You will use the with statement and the open method of a Path when you need to process large files line by line instead of loading them all into memory.
You will practise with a small configuration file and a log file in a practice folder.
By the end of this lecture you will be able to read and write text and binary files safely, set encodings and avoid partial writes.
Renaming hundreds of files by hand is exactly the kind of work automation should do. But a mistake in a rename script can scramble a folder in seconds. In this lecture you will batch rename files with a dry-run flag, so that you can see the plan before anything changes.
You will begin by defining a renaming rule, such as adding a date prefix, replacing spaces with underscores, converting names to lowercase and numbering files in sequence. You will write the rule as a function that takes a path and returns the new name, which keeps the logic separate from the act of renaming.
Next you will build a plan. A function collects the files in a folder, applies the rule and returns a list of pairs of old and new paths. It detects problems before anything is touched, such as two files that would end up with the same name or a new name that already exists in the folder.
You will print the plan clearly, then add the dry-run flag from your command-line lessons. When the flag is set, the script only reports what would happen. Without it, it applies the plan using the rename method, logging each step.
You will test on a practice folder of invented files, check the results and learn how to write an undo record, a small JSON file that lists every change so that you can reverse it if needed.
By the end of this lecture you will be able to plan, preview and apply batch renames safely with collision checks and an undo log.
Copying and moving files is a basic need for backups, deployments and organising downloads. Python's shutil module provides high-level operations that go beyond what pathlib offers. In this lecture you will copy and move files with shutil.
You will begin with copying a single file. You will compare shutil.copy, which copies the contents and permissions, with shutil.copy2, which also keeps timestamps and other metadata, and understand when each is appropriate. You will see what happens when the destination is a folder and when it is a file name.
Next you will copy entire folders with shutil.copytree. You will use the ignore parameter with ignore_patterns to skip items such as temporary files and caches, and the dirs_exist_ok option to merge into an existing folder. You will also see why copying a tree onto an existing path without that option raises an error.
Then you will move files and folders with shutil.move and learn how it behaves when the source and destination are on different drives, where it copies and then deletes. You will use shutil.rmtree to remove folders, with a strong warning about the danger of deleting the wrong path, and you will build a habit of printing and confirming the target first.
You will tie these together in a script that copies new files from one folder to another, skipping those that already exist, and logs each action.
By the end of this lecture you will be able to copy, move and remove files and folders with shutil, and apply careful safeguards.
Archives make files easier to store and send, and they are a natural step in backup routines. In this lecture you will archive directories with shutil.make_archive and learn how to build a simple, dated backup.
You will begin with the formats that shutil supports, including zip and tar files with different compression. You will compare their strengths: zip is widely understood on every platform, while tar with gzip is common on Linux and keeps file permissions more faithfully.
Next you will call make_archive with a base name, a format and the folder to archive. You will understand the roles of root_dir and base_dir, which control what the paths inside the archive look like and are a frequent source of confusion. You will check the result by listing the archive's contents with the zipfile or tarfile modules, and by unpacking it into a different folder with shutil.unpack_archive.
You will then build a small backup script. It creates a name that includes the current date and time, archives a chosen folder into a backup directory, logs the size of the file and removes archives older than a set number of days to avoid filling the disk. You will add a dry-run option, and you will write the timestamp with an injected value so that the behaviour can be tested.
You will also discuss safety when extracting archives from unknown sources, since paths inside them can be crafted to escape the target folder.
By the end of this lecture you will be able to create, inspect and extract archives and write a simple rotating backup script.
How can you tell whether a file has changed, been corrupted during a copy or is identical to another? Comparing names or sizes is not enough. A hash, a short fingerprint calculated from the contents, answers the question reliably. In this lecture you will hash files for integrity checks with hashlib.
You will begin with what a hash function does. It turns data of any size into a fixed-length value, so that even a tiny change produces a completely different result. You will compute the SHA-256 hash of a short string and see how a single altered character changes the entire output.
Next you will hash files. Reading a large file into memory all at once is wasteful, so you will read it in chunks, such as sixty-four kilobytes at a time, and feed each chunk to the hash object using update. You will finish with hexdigest to get the printable value. You will wrap this in a reusable function that takes a path and an algorithm name.
You will use it for integrity checking. You will create a manifest, a JSON file that records each file's relative path and hash, and then write a verification function that recalculates the hashes and reports files that are missing, changed or new.
You will discuss why you should prefer SHA-256 over older algorithms such as MD5 when integrity matters.
By the end of this lecture you will be able to compute file hashes efficiently, build manifests and verify folders against them.
Over time, folders fill up with copies of the same file under different names, wasting space and creating confusion. Finding them by name is unreliable, but contents do not lie. In this lecture you will deduplicate files by hash.
You will begin with the strategy. Comparing every file with every other file would be very slow, so you will work in stages. First you group files by size, because files of different sizes cannot be identical. Within each group of equal size, you compute a hash and group by that. Files that share both size and hash are duplicates.
Next you will write the scanner with pathlib and a dictionary of lists. It walks a folder with rglob, ignores directories and unreadable files, groups by size and hashes only the groups that contain more than one file. You will reuse the chunked hashing function from the previous lecture.
You will produce a report that lists each set of duplicates with their sizes and the amount of space that could be recovered. You will decide which copy to keep by a clear rule, such as the oldest, the shortest path or the first alphabetically.
Because deleting is risky, the script will not remove anything by default. It offers a dry-run listing and an option that moves duplicates into a quarantine folder instead of deleting them, so that mistakes can be reversed.
You will test with a practice folder of invented files containing known duplicates.
By the end of this lecture you will be able to find duplicates efficiently and handle them safely.
This lecture brings together the skills from the section into a practical tool: a file organiser driven by a JSON configuration. Downloads folders and shared drives often become a mess, and a script that sorts files into tidy subfolders is a classic automation project.
You will begin by designing the configuration. It maps categories to lists of file extensions, such as images, documents, spreadsheets and archives, and names a folder for each. It also has an other category for anything that does not match, a list of files to ignore and settings for a source folder and a destination folder.
Next you will write the pieces. A function loads and validates the configuration, a function decides the category for a path from its suffix, comparing in lowercase, and a planning function builds a list of moves without touching anything. A final function carries out the plan with shutil.move, creating destination folders as needed and handling name clashes by adding a number to the file name.
You will wire everything to a command-line interface with options for the config path, a dry-run flag and a verbosity level, and add logging that records every decision. You will finish with a summary that counts the files moved in each category.
You will test the organiser on a practice folder of invented files, first with the dry run and then for real, and read the log to confirm what happened.
By the end of this lecture you will be able to combine configuration, planning, safe file operations and logging into a complete, reusable tool.
CSV files are the common language of data exchange. Spreadsheets, exports and reports are almost always available in this format, and Python's csv module makes them easy to handle. In this lecture you will read and write CSV files with DictReader and DictWriter.
You will begin with a small invented sales file. You will open it in a text editor to see the header row, the commas and how text with commas inside is wrapped in quotation marks, which is the reason you should never split lines by hand.
Next you will read the file with csv.DictReader. Instead of lists of positions, every row becomes a dictionary keyed by the header names, so that your code says row of amount rather than row of index three. You will open the file with newline set to an empty string and an explicit encoding, as the documentation recommends, and see how all the values arrive as text, which means that numbers must be converted before you can calculate with them.
Then you will write a new file with csv.DictWriter. You will define the field names, call writeheader and write rows one at a time or with writerows. You will filter rows, add a calculated column and choose a different delimiter to see that the same code handles semicolon separated files.
You will also handle missing columns and extra columns gracefully, and report problems with the row number.
By the end of this lecture you will be able to read and write CSV data as dictionaries, convert types and transform rows safely.
Reports usually ask questions such as how much was sold in each region or how many orders each customer placed. Answering them means grouping rows and adding up values. In this lecture you will sum CSV columns by category using plain Python.
You will begin with the sales data from the previous lecture, which has columns for the date, region, product and amount. You will state the goal: a table showing the total for each region.
Next you will write the aggregation with a dictionary. For each row, you will convert the amount to a number, use the region as the key and add to the running total. You will see how defaultdict removes the need to check whether a key exists, and how the Decimal type avoids floating point surprises when you add money values. You will skip rows with missing or invalid amounts, count them and report them at the end instead of failing silently.
You will extend the idea to group by two columns, such as region and product, using tuples as keys, and to compute counts and averages as well as totals. You will sort the results in descending order and write them to a new CSV file with DictWriter.
You will finish by comparing your result with what a spreadsheet pivot table would show, which is a good way of checking your logic.
By the end of this lecture you will be able to group and total CSV data by category, handle bad rows and write the summary to a file.
Excel workbooks are everywhere in business, and being able to create them from a script is a valuable skill. The openpyxl library lets you build workbooks without opening Excel at all. In this lecture you will create an Excel workbook with openpyxl.
You will begin by installing the library and creating a Workbook object. A new workbook has one active worksheet, which you will rename, and you will add further sheets with create_sheet. You will learn the vocabulary: workbook, worksheet, row, column and cell.
Next you will write data. You will set cell values by coordinate, such as A1, and by row and column numbers, and use append to add whole rows quickly. You will write a header row followed by invented sales data, and add a total using a formula string, so that Excel calculates it when the file is opened.
Then you will make the sheet readable. You will apply fonts, bold headings, fill colours, number formats for currency and dates, column widths and borders. You will freeze the top row so that the header stays visible and add an automatic filter. You will also see how to merge cells for a title.
You will save the workbook with save and then reopen it to check that the content is correct. You will mention the limitation that openpyxl does not calculate formulas itself.
By the end of this lecture you will be able to create worksheets, write values and formulas, apply formatting and save workbooks.
Automation often runs in the other direction too: you receive an Excel file and need to pull data out of it. In this lecture you will read Excel sheets row by row with openpyxl.
You will begin by opening a workbook with load_workbook. You will learn about the data_only option, which returns the last calculated results of formulas instead of the formula text, and the read_only mode, which uses much less memory for large files. You will list the sheet names and choose a sheet by name rather than relying on which one is active.
Next you will iterate over the rows with iter_rows. You will set min_row, max_row and the columns to read, and ask for values only, so that you receive plain tuples. You will treat the first row as the header and combine it with each data row to create dictionaries, which makes the rest of your code clear and consistent with the CSV work you have already done.
You will deal with the realities of spreadsheets. Some cells are empty, some contain dates that arrive as datetime objects, some numbers are stored as text and some rows at the bottom are blank or hold notes. You will write a reader that stops at the first fully empty row and cleans the values.
You will then export the result to JSON or CSV, to show how Excel data can feed other automation steps.
By the end of this lecture you will be able to open workbooks, iterate rows efficiently and convert sheet data into clean records.
Many tasks end with a report that a person will read, and Word documents are a common format. The python-docx library lets you generate them from a script. In this lecture you will generate a Word report with python-docx.
You will begin by installing the library and creating a Document. You will learn how a document is built from paragraphs, runs and styles, where a run is a piece of text with its own formatting, such as a bold word inside a sentence.
Next you will add content. You will write a title with a heading, add paragraphs, apply bold and italic formatting to runs and create bulleted and numbered lists using the built-in styles. You will insert a table, fill it from a list of dictionaries, set a table style and make the header row bold. You will add a picture, such as a chart saved by another tool, and set its width.
Then you will set document properties, such as the author and title, and control the page layout, including margins and orientation. You will add a header and footer that carry the report name and a date.
You will build the report from the sales summary produced earlier, so that the data flows from CSV to a finished document without any manual copying. You will save the file and open it to check the result.
By the end of this lecture you will be able to create structured Word documents with headings, formatted text, lists, tables and images.
PDF is the standard format for documents that need to look the same everywhere, such as invoices, certificates and reports. The reportlab library lets you create them directly from Python. In this lecture you will create a PDF report with reportlab.
You will begin with the two levels of the library. The low-level canvas lets you place text and shapes at exact coordinates, while the higher-level platypus framework flows content across pages automatically, which is much better for reports of unknown length.
Next you will start with the canvas, creating a page, drawing a title, a line and some text, and understanding that the origin of the coordinate system is the bottom left corner and that units are points. You will see how to change fonts and colours.
Then you will use platypus. You will build a SimpleDocTemplate, create a list of flowables, such as paragraphs with styles, spacers and tables, and call build. You will construct a table from the invented sales summary, style it with a header colour, grid lines and aligned numbers, and let it break across pages if it grows large. You will add page numbers using a footer function that runs on every page.
You will check the finished file by opening it and discuss how to handle long text safely, including escaping special characters in paragraphs.
By the end of this lecture you will be able to generate multi-page PDFs with styled text, tables and page numbers.
Sometimes you receive information locked inside a PDF, such as an invoice, a statement or a report, and you need the text out of it. The pypdf library can read PDFs and extract text. In this lecture you will extract text from a PDF with pypdf.
You will begin by understanding what a PDF contains. It is a layout format, not a text format. Text is placed on the page in fragments, which means that extraction gives you an approximation of the reading order, and that scanned pages, which are only images, contain no text to extract.
Next you will open a practice PDF, generated by you in the previous lecture so that no external document is needed, with PdfReader. You will find the number of pages, read the metadata such as the title and author and loop through the pages calling extract_text. You will print the text, look at how line breaks and spacing behave and clean it up with string methods and regular expressions.
You will then use the text for automation. You will search for keywords, pull out a date or an invoice number with a pattern and write the results to a CSV file, as a small example of a document processing task. You will handle encrypted files by checking is_encrypted and supplying a password only when you are authorised to do so.
You will also discuss when text extraction will not work and OCR would be needed.
By the end of this lecture you will be able to read PDF metadata, extract text and use patterns to pull out structured data.
Combining several PDFs into a single document is a common office task, such as assembling an application pack or a monthly report from separate parts. In this lecture you will merge multiple PDFs into one using pypdf.
You will begin by creating a few practice PDFs with reportlab, so that you have known inputs with different numbers of pages. You will inspect each one and note the page counts.
Next you will use PdfWriter to build the output. You will loop over a list of input files, open each with PdfReader and add the pages with add_page. You will compare this with the append method, which adds the whole document in one call and can take a page range, and use it to include only selected pages. You will write the result to a new file and confirm that its page count equals the sum of the parts.
You will add finishing touches. You will add bookmarks, called outline items, that point to the first page of each source file, set the title in the metadata and rotate a page that was in the wrong orientation. You will sort the inputs by name so that the order is predictable.
You will then wrap everything in a command-line tool that accepts a folder, a pattern and an output name, validates the inputs and logs the files it processed.
You will handle errors, such as an unreadable or encrypted file, without losing the work done so far.
By the end of this lecture you will be able to merge PDFs, select page ranges, add bookmarks and build a reusable merge tool.
Web pages are written in HTML, and to extract information from them you need to turn that text into a structure you can search. BeautifulSoup is the most popular Python library for the job. In this lecture you will parse HTML with BeautifulSoup.
You will begin with a note on responsible scraping. In this course you will work mainly with HTML saved in strings and files that you create yourself, so that the exercises run offline and never put load on anyone's server. When you scrape real sites, you should check their terms of use and robots.txt, limit your request rate and prefer an official API whenever one exists.
Next you will install the library and create a BeautifulSoup object from a short HTML document, choosing the built-in html.parser. You will see how the parser turns the text into a tree of tags, attributes and text, and how it copes with untidy markup, such as unclosed tags.
You will navigate the tree. You will read the title, access the first tag of a given name, read its text with get_text and its attributes with get, and move to parents, children and siblings. You will print the document with prettify to see the structure that the parser has built.
You will also learn the difference between a tag, a string and the soup object, which clears up many beginner errors.
By the end of this lecture you will be able to parse HTML into a tree, read text and attributes and navigate between elements.
Once you have a parsed page, the next skill is finding exactly the elements you need. BeautifulSoup offers two core methods for this, find and find_all. In this lecture you will use them to locate data in a page.
You will begin with a sample HTML page, written for the course, that resembles a small product listing with headings, links, paragraphs and a list of items. You will study the markup so that you can describe each target in terms of its tag name, class and attributes.
Next you will use find to return the first match and find_all to return a list of all matches. You will search by tag name, by the class_ argument, by id and by arbitrary attributes using a dictionary. You will pass a list of names to match several tags, use a regular expression to match patterns and supply a function for custom conditions. You will limit the number of results and restrict a search to the descendants of an element you have already found.
You will extract useful values. For each item, you will read its text, strip whitespace and pull out the link address with the href attribute. You will deal with the common problem of an element that is missing, by checking for None before calling methods on the result.
You will collect the results into a list of dictionaries and print them as JSON.
By the end of this lecture you will be able to find single and multiple elements by tag, class, id and attributes, and extract their text and links safely.
Searching by tag and class works, but CSS selectors are often shorter and clearer, especially for nested structures. If you have ever styled a web page, you already know the syntax. In this lecture you will target data with CSS selectors in BeautifulSoup.
You will begin by reviewing the selector basics. A tag name selects elements of that type, a dot selects a class, a hash selects an identifier, a space selects descendants, a greater-than sign selects direct children and square brackets select attributes. You will see how these combine, so that one expression such as a div with a class, then a link inside it, describes a precise location.
Next you will use the select method, which returns a list, and select_one, which returns the first match or None. You will rewrite several of the find and find_all searches from the previous lecture as selectors and compare the readability.
You will explore more advanced selectors, including the nth-child pseudo-class for picking a row by position, attribute operators for matching the start or end of a value and selectors for elements that have a particular attribute. You will discuss how to choose selectors that are stable, avoiding long fragile chains that depend on the exact layout of a page.
You will practise by extracting names, prices and links from a sample page and cleaning the values, for example converting a price string to a number.
By the end of this lecture you will be able to write and test CSS selectors and extract structured data from nested HTML.
Tables are one of the most valuable things to scrape, since they already have a structure of rows and columns. In this lecture you will scrape an HTML table into records that you can save or analyse.
You will begin by examining the markup of a table in a sample page that you create. You will identify the table element, its header row in thead or th cells, the body rows in tr elements and the data cells in td elements, and note the tricky parts such as cells that span several columns.
Next you will write a function that takes the HTML of a table and returns a list of dictionaries. It reads the header cells to obtain the column names, loops over the body rows and pairs each row's cell values with the headers. You will strip whitespace, convert numbers and percentages to proper types and treat empty cells as missing values.
You will make the function robust. It should cope with a table that has no explicit thead, rows with the wrong number of cells and nested elements such as links inside cells, from which you may want both the text and the address.
You will then save the records as CSV and JSON, and compare with using pandas read_html, which can read tables in a single line, discussing when each approach is better.
You will test on pages with several tables, selecting the right one by caption or identifier.
By the end of this lecture you will be able to convert HTML tables into clean, typed records and export them.
Before sending a request to a website or an API, you can build it, inspect it and check that it is correct without sending anything. This is a safe way to develop and test automation. In this lecture you will build requests without sending them, using the requests library.
You will begin with the reasons. Sending requests while you are still developing can hit rate limits, cost money or change data. If you can prepare a request and look at it first, you can find mistakes early and write tests that need no network.
Next you will create a Request object and call prepare to get a PreparedRequest. You will set the method, the URL, query parameters, headers and a JSON body, and then inspect the final URL, the encoded query string, the headers that were added and the body bytes. You will see exactly how parameters are encoded and how special characters are escaped.
You will learn about sessions, and how default headers and settings in a Session are merged into each request. You will add a custom user agent that identifies your script honestly, and a timeout that you will always provide so that a stalled server cannot hang your program.
You will write a function that builds a request from a configuration and returns it, and test it with assertions, comparing the prepared URL and headers with the expected values.
By the end of this lecture you will be able to prepare and inspect requests, use sessions and test request-building logic without any network access.
Some pages build their content with JavaScript after they load, which means that simple HTML parsing sees an empty shell. A real browser is needed, and Playwright lets you control one from Python. In this lecture you will launch a headless browser with Playwright.
You will begin by explaining what headless means. The browser runs without a visible window, which is ideal for scripts and servers, while behaving like a real browser underneath, including running scripts and applying styles.
Next you will install the playwright package and download the browser binaries with the install command. You will use the synchronous API with a context manager, start Chromium, open a new page and navigate to a local HTML file or a page served from your own machine, so that the exercise is independent of any outside website. You will read the page title and the content, and take a screenshot to see what the browser saw.
You will learn about the structure of browser, context and page, and why contexts are useful for isolating sessions. You will set the viewport size, a user agent and a timeout, and close everything properly using the with statement or a finally block so that no browser processes are left running.
You will also try headed mode, where the window is visible, as a debugging aid.
By the end of this lecture you will be able to install Playwright, launch a headless browser, load a page and capture a screenshot.
Once a page is loaded in the browser, you need to pull information from it. Playwright uses locators, which describe how to find elements and are designed to be robust. In this lecture you will read page content with locators.
You will begin with a local sample page, written for the exercise, that contains headings, links, a list and a form. You will create locators with the page.locator method using CSS selectors, and with the more readable helper methods such as get_by_role, get_by_text and get_by_label. You will see why selecting by role and visible text is often more stable than depending on a class name that a designer might change.
Next you will read from locators. You will use inner_text and text_content for text, get_attribute for attributes such as a link address and count to see how many elements match. You will loop over multiple matches with all and nth, and narrow a search by chaining locators, for example finding a button inside a particular row.
You will understand that locators are lazy. They find elements when you act on them, and they automatically wait for the element to be available, which removes the need for many manual sleeps.
You will also fill an input and click a button on the practice page to see how interaction works, then read the result.
By the end of this lecture you will be able to find elements with different locator strategies and read their text and attributes.
Modern websites often show a placeholder first and fill in the data a moment later with JavaScript. If your script reads the page too early, it finds nothing. In this lecture you will wait for JavaScript-rendered content correctly.
You will begin by building a local test page that simulates the situation. A script in the page adds items to a list after a short delay, as a real application would after fetching data. You will load it and read the list immediately, and see that it is empty, which reproduces a common automation bug.
Next you will learn why fixed sleeps are a poor answer. They are either too short, which causes failures, or too long, which wastes time. Instead, you will wait for a condition. Playwright's locators already wait for elements when you act on them, and you will use wait_for on a locator to wait for it to become visible, attached or hidden.
You will use wait_for_selector, wait_for_load_state and expect-style checks, and learn the difference between the load event and network idle. You will set explicit timeouts and handle TimeoutError with a helpful message that says what the script was waiting for.
You will also wait for a text change, a count of elements to reach a number and a loading spinner to disappear, and discuss which condition best shows that the data is truly ready.
By the end of this lecture you will be able to wait reliably for dynamic content and handle timeouts.
This section ends with a complete workflow that combines scraping skills: visiting several pages in a sequence, collecting data from each and saving it as JSON. In this lecture you will build a multi-step workflow with pagination and JSON output.
You will begin by setting up a local practice site made of a few simple HTML pages, each listing items and including a next link, with the last page lacking one. This lets you practise pagination without touching any real website.
Next you will design the workflow in steps. Start at the first page, wait for the items to appear, extract each item's name, price and link, record them with the page number, and then look for the next button. If it exists, click it and wait for the new content, and if not, stop. You will protect against endless loops with a maximum page count and detect when the page did not change.
You will structure the code into small functions, one for extracting items from a page, one for moving to the next page and one for running the whole loop, with a clear data type for an item. You will add logging for each page and a polite delay between steps.
At the end, you will write the records to a JSON file with an indent, include metadata such as the run time and page count and check the results against the sample site.
You will also consider handling a failure partway through without losing the data already collected.
By the end of this lecture you will be able to automate a multi-page workflow with stopping conditions and structured output.
Automation scripts that talk to online services need credentials such as API keys and tokens. Where you keep them matters. A key written into your source code can be copied, shared by accident and pushed into a public repository. In this lecture you will keep API secrets in environment variables.
You will begin with the reasons. Code travels. It is emailed, committed and pasted into chats, and a secret inside it travels along. Environment variables live outside the code, belong to the process that runs it and can be different for each machine and each deployment.
Next you will read them in Python with os.environ and os.getenv, and see the difference between indexing, which raises a KeyError when the name is absent, and get, which returns a default. You will write a helper that reads a required variable and raises a clear error that names it, without ever showing the value, and another that handles optional settings with defaults and type conversion.
You will learn how to set variables for a terminal session on each operating system and how a local environment file can help during development, provided that it is listed in your ignore file for version control. You will use placeholder values in every example and never real keys.
You will also discuss masking a secret in logs, showing only a few characters at most, and rotating a key that may have been exposed.
By the end of this lecture you will be able to load credentials from the environment, fail clearly when they are missing and keep them out of your code and logs.
Most web APIs require you to prove who you are with each request, and a very common method is a bearer token in the Authorization header. In this lecture you will build a bearer token authorization header correctly.
You will begin with how the header works. The client sends a line such as Authorization with the word Bearer, a space and the token. The server checks the token and decides whether to allow the request. Because the token is effectively a password, it must be protected from exposure.
Next you will write a function that takes a token and returns a dictionary of headers. It will strip stray whitespace and newlines, which commonly cause mysterious authentication failures when a token is read from a file, reject empty values and add other standard headers such as Accept and a descriptive User-Agent. You will compare the result with other schemes, such as basic authentication and API keys in custom headers, and see how each is built.
You will use the prepared request technique from earlier to inspect the final request without sending it, and check that the token appears only where it should. You will then write a redacting function that replaces the token with a short mask when headers are logged, and test it.
You will use only placeholder tokens throughout the lecture.
By the end of this lecture you will be able to construct authorization headers, avoid common formatting errors and keep tokens out of your logs.
When an API replies, your script must turn the response into data it can use, and it must do so carefully. Servers can return errors, empty bodies or unexpected shapes. In this lecture you will parse a JSON API response body robustly.
You will begin with a saved sample response, held as a string so that no network is needed. It resembles the output of a typical service, with a status field, a list of items, nested objects and a metadata section. You will load it with the json module and explore the structure.
Next you will learn defensive techniques. You will use the get method with defaults instead of direct indexing, check types before iterating and write small helper functions that extract nested values by a path of keys and return a default when any step is missing. You will validate that the fields your program depends on are present and have the right types, and raise an error with a clear explanation if they are not.
You will also deal with the HTTP side. You will check the status code, treat non-success codes as errors, read the content type and handle a body that is not valid JSON by catching JSONDecodeError and logging a short, safe excerpt of the text.
You will convert the items into your own simple data class, so that the rest of the program does not depend on the exact shape of the API.
You will test with good and broken samples.
By the end of this lecture you will be able to parse and validate API responses and convert them into clean internal data.
APIs that return many records do not send them all at once. They divide them into pages, and cursor-based pagination is one of the most common designs. In this lecture you will walk cursor-based pagination to collect a complete set of results.
You will begin with the idea. Each response contains a page of items and a cursor, an opaque value that points to where the next page starts. You send that cursor back in the next request, and when the response contains no cursor, you have reached the end. This is more reliable than page numbers when data changes while you are reading.
To work without a network, you will write a fake API function that serves a list of invented records in pages and returns the cursor for the next one. Your client code will use it exactly as it would use a real service, which makes it possible to test every case.
You will write the loop. Start with no cursor, request a page, add its items to the results, read the next cursor and repeat until it is absent. You will write it as a generator that yields items one by one, so that the caller can stop early and memory use stays low. You will add safeguards: a maximum number of pages, detection of a repeated cursor that would cause an infinite loop and logging of progress.
You will test with empty results, a single page and many pages.
By the end of this lecture you will be able to implement cursor pagination safely and expose it as a generator.
APIs protect themselves with rate limits, and a script that sends requests too fast will receive a 429 Too Many Requests response. Handling that gracefully is the difference between a fragile script and a dependable one. In this lecture you will retry rate-limited calls with backoff.
You will begin by deciding what should be retried. Rate limit responses, temporary server errors such as 502, 503 and 504 and connection timeouts are usually transient. Errors such as 400, 401 and 404 will fail again, so retrying them wastes time. You will write a function that classifies a status code.
Next you will learn exponential backoff. After each failure, you wait longer, such as one, two, four and eight seconds, up to a maximum, which gives the service time to recover. You will add jitter, a small random variation, so that many clients do not retry at the same instant. You will also respect a Retry-After header when the server provides one, since it states exactly how long to wait.
You will write a retry function that takes a callable, the number of attempts and the delay settings. To keep it testable, you will inject the sleep function and the random source, so that tests run instantly and results are predictable. You will test it with a fake API that fails a chosen number of times before succeeding.
You will log each retry with the reason and the delay, and give up with a clear error after the final attempt.
By the end of this lecture you will be able to classify errors, apply exponential backoff with jitter and test retry logic without waiting.
A webhook is an API in reverse. Instead of your script asking a service for news, the service sends an HTTP request to you when something happens, such as a payment, a commit or a new message. In this lecture you will route a webhook payload by event type.
You will begin with the concept. A webhook delivers a JSON body that normally includes the type of event and the data about it. Your code needs to look at the type and run the right handler, ignoring events that it does not care about.
Next you will study a sample payload, written for the exercise, with fields for an event name, a timestamp and a nested data object. You will write a parser that validates the structure, checks for required fields and rejects anything malformed with a clear error.
Then you will build the router. A dictionary maps event names to handler functions, and a decorator registers a function for an event. The dispatch function looks up the handler, calls it with the data and returns a result. For unknown events, it logs a message and returns a harmless response, because most services expect a success status even for events you ignore, and they may retry if you fail.
You will discuss practical points such as responding quickly, doing slow work in the background and handling repeated deliveries by tracking event identifiers, which makes handlers idempotent.
You will test with several synthetic payloads.
By the end of this lecture you will be able to parse webhook payloads, route them to handlers and handle unknown and repeated events.
Anyone on the internet can send a request to your webhook address, so how do you know it really came from the service you trust? The standard answer is a signature. In this lecture you will verify webhook signatures with HMAC.
You will begin with the idea. The sender and receiver share a secret. The sender computes a keyed hash of the request body, called an HMAC, and sends it in a header. The receiver calculates the same value from the body it received and compares. If they match, the message is authentic and has not been altered.
Next you will use the hmac and hashlib modules. You will compute an HMAC with SHA-256 over the raw bytes of the body, using the secret as the key, and encode it as hex. You will emphasise that the calculation must use the exact raw bytes and not a re-serialised version of the JSON, because even a change in spacing alters the result.
You will compare signatures with hmac.compare_digest, which takes the same time however many characters match, and explain why an ordinary equality check can leak information. You will also parse header formats that include a timestamp and check that the timestamp is recent, which protects against replay of old messages.
You will write the verification function and test it with a made-up secret, a valid signature, a modified body and a stale timestamp.
You will never use a real secret in an example.
By the end of this lecture you will be able to compute and verify HMAC signatures, compare them safely and defend against replays.
Many automation jobs end by uploading files to cloud storage, such as a bucket in an object store. Before you do that for real, it pays to plan the upload: decide where each file will go and what it will be called. In this lecture you will plan a cloud upload with object keys.
You will begin with how object storage works. It has no real folders, only keys, which are strings that may contain slashes and are shown as folders by tools. A key must be unique within a bucket, and a sensible naming scheme makes files easy to find, sort and expire.
Next you will design the scheme. You will build keys from a prefix for the project, a date in year, month and day parts, the file's relative path and, optionally, part of its content hash, so that identical files can be recognised. You will normalise names by removing unsafe characters, avoiding leading slashes and rejecting path components that try to climb out of the prefix.
You will write a function that scans a local folder and returns an upload plan, a list of records with the local path, the object key, the size and the content type guessed from the extension. You will detect duplicate keys and files that are too large for a single upload.
Because this is a plan, nothing is sent. You will print it as a table and save it as JSON, and then show how a real upload step, using a cloud library, would read the plan.
By the end of this lecture you will be able to design object keys and produce a safe, reviewable upload plan.
Email is still one of the most widely used channels for automation, whether for reports, alerts or confirmations. Python can build messages with the standard library. In this lecture you will compose an email message object with the email package.
You will begin with the anatomy of a message. It consists of headers, such as From, To, Subject and Date, and a body, which may be plain text, HTML or both. Attachments are additional parts.
Next you will use EmailMessage. You will set the headers with dictionary-style assignment, add a plain text body with set_content and an HTML alternative with add_alternative, so that mail programs can choose what to display. You will format addresses properly with the email.utils helpers, set a date with formatdate and a message identifier with make_msgid.
Then you will add an attachment. You will read a file, guess its type with mimetypes and attach it with add_attachment, supplying the main type, subtype and file name. You will examine the finished message by printing it as a string and look at how the structure changes when parts are added.
You will think about safety. Header values must not contain stray new lines that could allow header injection, and the library helps by rejecting them. You will also discuss writing clear subjects and including a plain text version for accessibility.
You will test the builder function with placeholder addresses, and no mail is sent.
By the end of this lecture you will be able to create plain, HTML and attachment-bearing messages and inspect them safely.
Once a message is composed, you need to send it. The smtplib module speaks the protocol that mail servers use, but sending mail from a script that is still being developed is risky. In this lecture you will send email with smtplib behind a dry-run switch.
You will begin with the sending steps. Connect to a server, start an encrypted session with starttls or connect directly over SSL, log in, send the message and quit. You will use the context manager form so that the connection is always closed, and create a default SSL context for secure settings.
Next you will design the safety switch. A function takes the message and a configuration and, when dry-run is on, which should be the default, it logs the recipients, the subject and the size, and returns without any network activity. Only when the switch is deliberately turned off does it connect. You will connect the switch to the command-line flag from earlier.
You will load the server name, port, username and password from environment variables, never from code, and handle the errors that can occur, such as authentication failure, refused recipients and timeouts, with clear messages. You will set a timeout on the connection.
To test the real path without a real server, you will use a fake SMTP class that records what it receives, and pass it in as a parameter. This is a form of dependency injection that makes the sending logic fully testable.
By the end of this lecture you will be able to send mail securely, protect against accidental sends and test the code without a mail server.
Automation often needs to read mail as well as send it, such as collecting reports from an inbox or filtering messages. In this lecture you will parse and filter incoming email using the email package.
You will begin with sample messages stored as text in files, so that no mailbox access is needed. You will read them with email.message_from_string or the policy-aware parser, which gives you convenient objects. You will inspect the headers, including From, To, Subject and Date, and parse the address and the date with email.utils.
Next you will extract the body. A message can have several parts, so you will walk through it with walk and select parts by content type. You will use get_body to find the preferred plain text or HTML version, decode it with the right character set and strip markup when necessary. You will also list attachments, read their file names and save them to a folder, taking care to clean the names so that they cannot write outside the target directory.
Then you will write filters. A rule is a function that returns true or false for a message, based on the sender, words in the subject or the presence of an attachment. You will combine rules, apply them to a folder of messages and move matches into a separate folder or print a summary.
You will mention that real mailbox access uses the imaplib module, and that credentials belong in environment variables.
By the end of this lecture you will be able to parse messages, extract text and attachments safely and apply filter rules.
Slack is a common destination for automation alerts, and an incoming webhook is the simplest way to post to it. In this lecture you will send Slack alerts with an incoming webhook, building the request so that it can be tested safely.
You will begin with how an incoming webhook works. Slack gives you a unique URL. Sending a JSON message to it with a POST request posts text into a chosen channel. Because that URL acts like a password, anyone who has it can post messages, so it must be stored in an environment variable and never shown in logs or committed to a repository.
Next you will write a function that builds the payload. A basic message has a text field, and richer messages use blocks with headings, sections and fields. You will create a helper for an alert with a severity, a title and details, and use different emoji-free labels for information, warning and error. You will escape special characters in the text as the service requires.
You will use the prepared request approach to build the POST request, including the content type and a timeout, and show it without sending. Then you will add the sending function with a dry-run default, error handling for failed responses and a retry for rate limits using the backoff helper from earlier.
You will test with a fake session that records the request, using a placeholder address.
By the end of this lecture you will be able to build Slack messages, protect the webhook address and send alerts through a testable function.
Telegram bots offer another simple way to send alerts to a phone or a group. They use an HTTP API that is easy to call from Python. In this lecture you will send Telegram alerts with the Bot API.
You will begin with how the API is organised. After creating a bot through the official bot management process, you receive a token. Every call goes to a URL that contains the token, and the method name follows, such as sendMessage. You will also need the identifier of the chat that should receive the message. Because the token grants control of the bot, it must be kept in an environment variable and masked in every log, including the URL.
Next you will build the request for sendMessage. You will create the payload with the chat identifier, the text and options such as the parse mode, and learn why special characters must be escaped when using formatting modes. You will see the limits, such as the maximum length of a message, and write a function that splits a long report into several messages.
You will use the prepared request technique to inspect the request without sending it, and write a masking function that hides the token in the URL. You will then add the send function with a dry-run default, response checking, because the API returns a JSON object with an ok flag, and rate limit handling.
You will test with a fake session and placeholder values.
By the end of this lecture you will be able to compose Bot API requests, protect the token and send alerts safely.
Text messages reach people who are away from their desks, and several providers let you send them through a simple web API. Many of those APIs expect form-encoded data rather than JSON. In this lecture you will send SMS alerts with a form-encoded request.
You will begin with the difference between the two formats. A JSON body is sent with the content type application slash json, while a form-encoded body is a string of key and value pairs joined with ampersands and sent with application slash x-www-form-urlencoded. You will see how the requests library produces it when you pass a dictionary through the data parameter, and how special characters, spaces and plus signs are percent-encoded.
Next you will build a request for a typical provider-style endpoint. The payload contains the destination number, the sender and the message body, and the account credentials are sent with basic authentication. You will validate phone numbers against the international format, strip spaces and reject invalid values before any request is made, and enforce a length limit on the message, splitting or shortening as needed.
You will prepare the request and inspect the encoded body and headers without sending anything. You will then write a send function with a dry-run default, clear error handling for rejected numbers and failed authentication and careful logging that hides most of the phone number and all credentials.
You will use placeholder numbers and a fake session in every test.
By the end of this lecture you will be able to build form-encoded requests, validate input and send messages through a safe, testable function.
Automation frequently means running something later or repeatedly. The standard library includes the sched module for scheduling events in the same program. In this lecture you will schedule one-off jobs with sched and a simulated clock.
You will begin with the scheduler itself. You create a scheduler object with a time function and a delay function, then add events with enter, which uses a delay, or enterabs, which uses an absolute time. Each event has a priority, an action and arguments. Calling run processes the queue in order.
The key technique of this lecture is the simulated clock. Instead of waiting for real time, you will create a fake clock class that holds a number and provides a time method that returns it and a sleep method that advances it. When you give these to the scheduler, a job set for an hour from now runs instantly, and the output is exactly repeatable. This makes scheduled behaviour easy to test, which is normally the hardest part.
You will schedule several jobs with different times and priorities and check the order in which they run, including two jobs at the same moment. You will cancel an event and learn how an action can schedule another one, creating a repeating job.
You will discuss the limits of sched, such as running only within one process and blocking while it waits.
By the end of this lecture you will be able to schedule one-off and repeating actions and test them without waiting.
Cron expressions are a compact way to describe schedules, such as every weekday at nine in the morning. Understanding them is valuable even when you use a tool that runs them for you. In this lecture you will match cron-style schedules against a fixed datetime.
You will begin with the format. A standard expression has five fields for the minute, hour, day of the month, month and day of the week. Each can be a number, a list separated by commas, a range with a dash, a step with a slash or an asterisk that means every value.
Next you will write a parser for a single field. Given the text and the allowed range, it returns the set of matching numbers. You will handle asterisks, lists, ranges and steps, validate that values are within bounds and raise clear errors for invalid input. You will write tests for each form.
Then you will write the matching function. It takes an expression and a datetime and returns true when every field matches. You will convert Python's weekday numbering to the convention of cron, where Sunday is zero, and discuss the unusual rule that when both the day of the month and the day of the week are restricted, a match on either one is enough.
Because the function receives the datetime as an argument instead of reading the clock, tests can use fixed moments and be deterministic. You will then show a small loop that checks each minute.
By the end of this lecture you will be able to parse and match cron expressions and test schedule logic precisely.
Many automation tasks spend most of their time waiting for disks or networks, and running them one after another is slow. Threads allow several to overlap. In this lecture you will parallelise file work with ThreadPoolExecutor.
You will begin with the reason threads help here. Python has a global interpreter lock that prevents threads from running Python code at the same time, but while one thread waits for input or output, others can proceed. Tasks such as reading many files, downloading and calling APIs benefit.
Next you will use concurrent.futures. You will create a ThreadPoolExecutor with a limited number of workers, submit functions with submit and gather results with as_completed, and compare it with map, which keeps results in the order of the inputs. You will measure the time for a sequential version and a threaded version of a task such as hashing many files, and see the improvement.
You will handle errors properly. Exceptions inside a worker are stored in the future and raised when you ask for the result, so you will wrap that call and record failures without stopping the whole batch. You will choose a sensible number of workers, avoiding values so large that they overwhelm the disk or a server.
You will also learn about shared state and why you should return results from workers rather than modifying shared lists, or protect shared data with a lock when needed.
You will test with a practice folder of invented files.
By the end of this lecture you will be able to run tasks concurrently with threads, handle errors and measure the benefit.
Some automation tasks are not limited by waiting but by computation, such as compressing data, processing images or calculating hashes of large buffers. Threads do not help much with this work in standard Python. Processes do. In this lecture you will run CPU-bound work with ProcessPoolExecutor.
You will begin with the global interpreter lock and why it prevents threads from using several processor cores for Python code. Separate processes each have their own interpreter and memory, so they can run in parallel on different cores.
Next you will use ProcessPoolExecutor, which shares its interface with the thread version, making it easy to switch. You will write a function that performs a heavy calculation, such as counting primes in a range, and run it for a list of inputs. You will compare the time of a sequential run, a thread pool and a process pool, and see that only the process pool gives a real speed-up.
You will learn the requirements and costs. Functions and arguments are sent between processes by pickling, so they must be defined at the top level of a module, and large data is expensive to copy. On some systems, you must protect the entry point with the main guard, otherwise worker processes would start the program again. You will use the chunksize option of map to reduce overhead.
You will discuss how to choose the number of workers, using os.cpu_count as a starting point, and how to handle exceptions and cancellations.
By the end of this lecture you will be able to run CPU-heavy work in parallel and decide between threads and processes.
Asynchronous programming offers another way to handle many waiting tasks, using a single thread and cooperative switching. In this lecture you will run concurrent tasks with asyncio.
You will begin with the basic ideas. A coroutine is defined with async def, and it can pause at await points to let other coroutines run. An event loop schedules them. This is very efficient for work that is dominated by waiting, such as network calls, because thousands of waiting tasks cost very little.
Next you will write coroutines that simulate slow operations with asyncio.sleep, and run them with asyncio.run. You will first await them one after another and see the total time add up, then run them together with asyncio.gather, and see the total shrink to the length of the slowest one. You will create tasks with create_task, and use asyncio.wait_for to impose a timeout and handle the resulting error.
You will limit concurrency with a semaphore, which is essential when you must not overwhelm a service with too many simultaneous calls. You will collect results and exceptions with gather using return_exceptions, so that one failure does not hide the others.
You will also learn the main pitfall: calling blocking functions inside a coroutine freezes the whole loop. You will see how to run them in a thread with asyncio.to_thread.
By the end of this lecture you will be able to write coroutines, run them concurrently, apply timeouts and limit parallelism.
Network calls, files on shared drives and external services fail occasionally, and a robust automation script expects that. Instead of writing retry loops in every function, you can write the logic once as a decorator. In this lecture you will make flaky functions retry with a decorator.
You will begin with a quick review of decorators. A decorator is a function that takes a function and returns a wrapped version. You will see how functools.wraps keeps the original name and documentation, which matters for logging and debugging.
Next you will write a retry decorator that accepts parameters, such as the number of attempts, the initial delay, the backoff factor and the types of exceptions that should trigger a retry. This requires a decorator factory, a function that returns the decorator, and you will walk through the three layers carefully.
Inside the wrapper, you will loop over the attempts, call the function, return the result on success and, on a listed exception, log a message, wait using an injected sleep function and try again. After the last attempt, you will re-raise the final exception so that the failure is visible and the original traceback is preserved. You will make sure that exceptions that are not on the list pass through immediately.
You will test with a function that fails a chosen number of times before succeeding, using a fake sleep, and verify the count and delays. You will apply it to a file copy and an API call.
By the end of this lecture you will be able to write parameterised decorators and use them to add reliable retries.
Long-running jobs sometimes crash halfway, such as when a laptop goes to sleep or a server restarts. Starting again from the beginning wastes time and may repeat work that should not be repeated. In this lecture you will recover from crashes with a checkpoint file.
You will begin with the idea. A checkpoint records how far the job has progressed, such as the identifiers of the items already finished. When the job starts, it reads the checkpoint, skips completed items and continues with the rest.
Next you will design the checkpoint file as JSON, holding the set of completed items, a start time and the last update time. You will write functions to load it, returning an empty state if it does not exist or is damaged, and to save it. You will use the safe write pattern, writing to a temporary file and then replacing the original, so that a crash during the save cannot corrupt the checkpoint.
You will build a job that processes a list of invented work items, such as files to convert. After each item succeeds, it updates the checkpoint. You will simulate a crash by raising an exception partway through, then run the job again and see that it resumes from the right place and does not repeat completed items.
You will think about idempotence, meaning that repeating an action has the same effect as doing it once, and why it makes recovery safer. You will also add an option to reset the checkpoint and a cleanup step on success.
By the end of this lecture you will be able to save progress safely and resume interrupted jobs correctly.
Automation often means driving other programs: running a backup tool, calling git, compressing files or checking a service. Python's subprocess module lets your script start those programs and read what they produce. In this lecture you will run shell commands with subprocess.run.
You will begin with the basics. subprocess.run starts a command, waits for it to finish and returns a CompletedProcess object. You will pass the command as a list, such as the program name followed by its arguments, and examine the result's returncode, stdout and stderr attributes. A return code of zero conventionally means success, and anything else signals a problem.
Next you will capture output. You will set capture_output to true and text to true so that you receive strings instead of bytes, and learn what happens to the output when you do not capture it. You will use the cwd parameter to run a command in a particular folder, the env parameter to pass a modified environment and the input parameter to send text to the program's standard input.
You will protect against hangs by always providing a timeout and handling the TimeoutExpired exception. You will also learn why you should choose commands that exist on every platform for the exercises, such as running the Python interpreter itself, which keeps your examples portable.
You will write a small helper that runs a command, logs it and returns the cleaned output.
By the end of this lecture you will be able to run external programs, capture their output and handle timeouts.
A script that ignores a failed command and carries on can do real damage, such as archiving an empty folder because the copy step silently failed. The safer approach is to fail loudly. In this lecture you will use check equals True and handle CalledProcessError.
You will begin by demonstrating the problem. You will run a command that exits with a non-zero code, using the Python interpreter with a tiny program that exits with an error, and see that subprocess.run does not raise an exception by default. The script continues as if nothing had happened unless you look at the return code yourself.
Next you will pass check equals True. Now a failing command raises CalledProcessError, which carries the return code, the command, the output and the error output. You will catch it, log a clear message that includes the command and the captured stderr, and decide what to do: stop the pipeline, try again or continue with a warning.
You will compare two styles. One checks the return code manually and branches, which is useful when different codes have different meanings. The other uses check and exceptions, which is simpler when any failure should stop the work.
You will also handle the case where the program cannot be found at all, which raises FileNotFoundError, and the case where the command exceeds its timeout.
You will wrap this in a function that returns the output on success and raises a project-specific error on failure.
By the end of this lecture you will be able to detect and report command failures reliably and choose the right strategy for each.
Building a command by joining strings is one of the most common causes of security problems in scripts. If a file name or user input contains special characters, the shell can interpret them as commands. In this lecture you will build commands safely with argument lists.
You will begin by explaining the risk. When a command is run through a shell with shell equals True, the whole string is interpreted by the shell, which treats characters such as semicolons, ampersands, pipes and backticks as instructions. A file name containing one of them could cause a completely different command to run. You will demonstrate the effect harmlessly, using a command that only prints text, so that the danger is clear without causing any damage.
Next you will see the safe alternative. When you pass a list, each element is delivered to the program as exactly one argument, with no shell interpretation. A name containing spaces or special characters remains just a name. You will convert several string-based commands into lists and confirm that the behaviour is identical for normal input and safe for unusual input.
You will learn about shlex.split for converting trusted strings into lists, shlex.quote for the rare case that a shell is truly needed and the habit of validating input, for example allowing only expected characters or checking that a path lies inside a permitted folder.
You will also see how to use the double dash convention to prevent a value starting with a hyphen being treated as an option.
By the end of this lecture you will be able to build commands from lists, avoid shell injection and validate the values you pass.
Disks that fill up are a classic cause of failed jobs, and monitoring free space is an easy and useful automation. The standard library can report it without any external tools. In this lecture you will inspect disk usage with shutil.disk_usage.
You will begin by calling shutil.disk_usage on a path. It returns a named tuple with the total, used and free space in bytes for the file system that contains that path. You will write a helper that converts bytes into readable units such as megabytes and gigabytes, and a function that calculates the percentage used.
Next you will turn the numbers into a check. You will define a threshold, such as a warning when less than twenty percent is free and a critical state when less than ten percent is free, and write a function that returns a status along with a message. You will read the thresholds from your configuration file and allow them to be overridden on the command line.
You will also measure the size of a particular folder by walking it with pathlib and adding up file sizes, skipping links and unreadable files. You will list the largest folders or files in a practice directory, which helps to find what is using the space.
You will write a script that checks several paths, logs the results and exits with a non-zero code when a threshold is crossed, so that a scheduler or monitoring tool can notice.
You will test the logic by passing in fake usage values.
By the end of this lecture you will be able to measure disk usage, apply thresholds and report problems through logs and exit codes.
Databases hold some of the most valuable data a script touches, and a backup is essential before any risky change. SQLite is a file-based database included in Python, and its sqlite3 module offers a safe way to copy it. In this lecture you will back up a SQLite database with sqlite3.
You will begin by creating a small practice database with a table of invented records, using sqlite3.connect, execute and commit. You will see that the database is a single file, and then discover why simply copying that file while another program is writing to it is dangerous, since you could capture it in the middle of a change.
Next you will use the backup method of the connection object. It copies the database page by page into another connection, handling locking correctly so that the result is a consistent snapshot. You will open the source and a destination, call backup, and close both with context managers. You will also see the pages and progress parameters that allow a large database to be copied in steps while reporting progress.
Then you will verify the result. You will open the backup, run the integrity_check pragma and compare row counts between the source and the copy. You will build a backup file name that includes a timestamp, write to a temporary name and rename it on success, and delete backups beyond a retention limit.
You will add logging and a dry-run flag.
By the end of this lecture you will be able to create consistent SQLite backups, verify them and manage retention.
A project's history is useful information for automation, such as release notes, changelogs and activity reports. Git can show it from the command line, and Python can read that output through subprocess. In this lecture you will read Git history with git log via subprocess.
You will begin by creating a small practice repository with a few commits from a script, so that the exercise does not depend on any existing project. You will set a local user name and email within the repository only, make some changes and create commits with different messages and dates.
Next you will run git log with a custom format. You will learn that the default output is meant for people, which makes it hard to parse, and that the pretty option with format placeholders gives you the hash, author, date and subject exactly as you choose. You will use a unit separator character between fields and a different one between records, so that unusual characters in messages cannot confuse the parser.
You will write a function that runs the command with an argument list, check equals True and a timeout, splits the output and returns a list of dictionaries, or a small data class, with the commit details. You will parse dates into datetime objects, filter by author or by a date range using command options and count commits per author.
You will turn the data into a short changelog in Markdown, grouped by date.
You will also handle a folder that is not a repository, using the error that Git returns.
By the end of this lecture you will be able to run Git commands from Python, parse their output reliably and build simple reports.
A script that grows into a long list of statements is hard to test and hard to change. The capstone starts by reorganising a complete automation pipeline into small stage functions. In this lecture you will split the pipeline into testable stage functions.
You will begin with the pipeline you will build: it reads files from an input folder, validates and transforms the data, writes a report, archives the inputs and prepares a notification. You will first look at a version written as one long script and list its problems: it mixes input and output with logic, it cannot be tested without real files and any change risks breaking something else.
Next you will define the stages. Each stage is a function that takes clearly defined inputs and returns clearly defined outputs, with no hidden global state. For example, a discovery stage returns a list of paths, a parsing stage turns text into records, a validation stage separates good records from bad ones, a transform stage computes the results and a report stage returns text or a file path. You will use data classes or typed dictionaries to describe what flows between stages.
You will separate pure logic from side effects, and push file and network operations to the edges, passing them in as parameters where needed. You will connect the stages in a simple run function that calls each in turn, passing results along.
You will run the pipeline on a practice folder and compare the result with the original script.
By the end of this lecture you will be able to decompose a script into stages with clear inputs, outputs and boundaries.
A pipeline that is split into stages can be tested one piece at a time. The standard library includes the unittest framework, which needs no installation. In this lecture you will test pipeline stages with unittest.
You will begin with the basics. A test case is a class that inherits from unittest.TestCase, and each method whose name starts with test is a test. You will use assertions such as assertEqual, assertTrue, assertRaises and assertIn, and see how a failing test shows the expected and actual values. You will run the tests from the command line with python -m unittest, and learn about discovery of test files.
Next you will write tests for each stage. For the parsing stage, you will give it sample text and check the records. For validation, you will provide good and bad records and confirm that each lands in the right group, including edge cases such as empty values and negative numbers. For the transform stage, you will use small data where you can calculate the answer by hand.
You will use the setUp method to prepare fresh data and tempfile to create temporary folders that are removed after each test, so that tests never touch real files and never affect each other. You will use unittest.mock to replace a function that sends a notification with a fake, and check that it was called with the right arguments.
You will also test failure paths, since they are where bugs often hide.
By the end of this lecture you will be able to write, organise and run unit tests with temporary files and mocks.
In this final lecture you will assemble everything from the course into a complete automation pipeline. The tested stage functions will be wired together with configuration, retries and dry-run notifications, producing a tool that you could run unattended.
You will begin with the entry point. A command-line interface built with argparse accepts the path to a configuration file, a dry-run flag, a verbosity level and optional overrides. The settings are merged using the precedence rules you learned earlier, validated and logged, with secrets hidden.
Next you will compose the run. Logging is configured first. The discovery stage finds the input files, and the parsing, validation and transform stages process them. Operations that might fail temporarily, such as fetching data or sending a message, are wrapped with the retry decorator and backoff. A checkpoint file records completed items, so that a rerun after a crash resumes instead of starting over.
You will add the output steps: the report is written safely, the inputs are archived with a timestamped name and a notification message is prepared for the chosen channel. In dry-run mode, the notification is only logged, and in a real run it is sent through the function that you can test with a fake session.
You will end with a summary that reports counts of processed, skipped and failed items and sets an exit code that a scheduler can read. You will run the pipeline against a practice folder, first as a dry run and then for real, and review the log.
By the end of this lecture you will be able to combine configuration, stages, retries, checkpoints and safe notifications into a reliable automation pipeline.
This course contains the use of artificial intelligence.
Are you ready to stop wasting hours on repetitive tasks and start building intelligent, efficient, and reliable automation solutions? Automate Everything with Python: 50 Real-World Projects is a comprehensive, hands-on course designed to help you master Python automation, scripting, web scraping, browser automation, API integration, task scheduling, and DevOps automation through practical coding exercises.
Whether you are a Python developer, software engineer, IT professional, data analyst, or technology enthusiast, this course will help you transform your programming knowledge into practical automation skills.
With 9 comprehensive modules and 61 hands-on lessons, you will progress from essential automation foundations to advanced, production-grade automation pipelines.
Begin by mastering Python scripting, virtual environments, command-line interfaces (CLI), argparse, JSON configuration management, and structured logging. Learn how to develop reusable, configurable, and maintainable Python applications that solve everyday business and technical challenges.
Explore file system automation, directory management, batch file processing, file organization, automated backups, file hashing, duplicate detection, and data wrangling using powerful Python libraries such as pathlib, shutil, and hashlib.
Discover how to automate everyday office tasks with Microsoft Excel automation, CSV processing, Word document generation, PDF automation, and automated reporting. Work with popular Python libraries, including openpyxl, python-docx, ReportLab, and pypdf, to transform raw data into useful business documents.
Master web scraping and browser automation using BeautifulSoup, Requests, Playwright, HTML parsing, CSS selectors, and headless browsers. Learn how to extract structured website data, automate form interactions, navigate paginated websites, and process JavaScript-rendered content.
Expand your technical capabilities with REST API integration, API authentication, bearer tokens, JSON processing, webhooks, HMAC signature verification, API pagination, rate limiting, exponential backoff, and cloud storage automation patterns. Develop secure and reliable approaches to integrating external services.
Build practical email automation, messaging automation, and notification systems using SMTP, Slack webhooks, Telegram Bot API, and SMS integration patterns. Learn how automated applications can generate alerts, deliver reports, and support business workflows.
Take your automation skills further with task scheduling, cron-style scheduling, multithreading, multiprocessing, concurrent programming, asynchronous programming, asyncio, ThreadPoolExecutor, and ProcessPoolExecutor. Improve application reliability through retry mechanisms, checkpointing, exception handling, and automated failure recovery.
Explore system administration automation, DevOps scripting, shell command execution, subprocess management, disk usage monitoring, SQLite database backups, and Git automation. These valuable skills can support careers in software engineering, automation engineering, IT operations, DevOps, and backend development.
Finally, bring everything together in a comprehensive capstone automation project. Build an end-to-end automation pipeline that integrates data extraction, data transformation, automated reporting, notification workflows, configuration management, retry mechanisms, and unit testing.
This course emphasizes project-based learning, practical Python programming, software engineering best practices, workflow automation, business process automation, and productivity improvement. Rather than focusing exclusively on theory, you will write Python code and develop solutions that can be adapted to real-world requirements.
The core exercises are designed around accessible Python tools and local workflows, helping you build valuable skills without requiring expensive software or paid cloud subscriptions.
Whether your goal is career advancement, freelance Python development, automation consulting, business productivity, or professional software development, this course provides a practical foundation for your next step.
Enroll today and discover how to make Python do the repetitive work for you. Build smarter workflows, strengthen your programming skills, reduce manual effort, and become a more confident Python automation developer.