How to Test Passkey Login with Playwright — WebAuthn Automation Guide

Passkeys are replacing passwords across the web, and if your test automation framework can’t handle WebAuthn flows, you’re already falling behind. Playwright 1.61 introduced browserContext.credentials — a virtual authenticator that lets you register, store, and use passkeys entirely in code. This guide walks you through everything you need to automate passkey login testing, with ready-to-use TypeScript examples.


🔐 What Is WebAuthn and Why Should QA Engineers Care?

WebAuthn (Web Authentication) is the W3C standard behind passkeys. Instead of passwords, users authenticate with biometrics (fingerprint, face recognition) or hardware security keys.

Major platforms — Google, Apple, Microsoft, and most modern SaaS products — now support passkey login. As a QA engineer or SDET, you’ll increasingly encounter apps that use WebAuthn, and your automation framework needs to test these flows reliably.

⚠️ The Problem: Traditional test tools couldn’t interact with hardware authenticators. You’d have to skip those tests or test them manually. Playwright 1.61 solves this completely with a built-in virtual authenticator!


📋 Prerequisites

Before we start, make sure you have:

  • ✅ Node.js 18 or later
  • ✅ Playwright 1.61+ installed
  • ✅ Basic knowledge of TypeScript and Playwright
# Install or upgrade Playwright
npm install @playwright/test@latest
npx playwright install

# Verify version
npx playwright --version

⚙️ Setting Up the Virtual Authenticator

Playwright’s virtual authenticator is available through browserContext.credentials. No additional setup is required — it’s built into the browser context.

import { test, expect } from '@playwright/test';

test('virtual authenticator is available', async ({ context }) => {
  // The credentials API is ready to use immediately
  const credentials = await context.credentials.list();
  expect(credentials).toEqual([]);
  console.log('Virtual authenticator is active!');
});

💡 Key Insight: The virtual authenticator behaves like a FIDO2-compliant security key. When a website triggers a WebAuthn ceremony (registration or login), Playwright’s authenticator responds automatically — no user interaction needed!


🔑 Registering a Passkey in Your Tests

Here’s how to automate passkey registration:

import { test, expect } from '@playwright/test';

test('register a new passkey', async ({ context, page }) => {
  // Navigate to your app's registration page
  await page.goto('https://your-app.com/settings/security');

  // Click the "Add Passkey" button
  await page.getByRole('button', { name: 'Add Passkey' }).click();

  // Playwright's virtual authenticator handles the WebAuthn ceremony
  // Wait for confirmation
  await expect(page.getByText('Passkey added successfully')).toBeVisible();

  // Verify the credential was stored
  const credentials = await context.credentials.list();
  expect(credentials.length).toBe(1);
  console.log('Credential ID:', credentials[0].id);
});

When the browser triggers navigator.credentials.create(), the virtual authenticator generates a key pair and responds with the public key credential — exactly as a real hardware key would.


🚀 Automating Passkey Login

Once a passkey is registered, testing the login flow is straightforward:

test('login with passkey', async ({ context, page }) => {
  // Step 1: Register a passkey
  await page.goto('https://your-app.com/register');
  await page.getByRole('button', { name: 'Register with Passkey' }).click();
  await expect(page.getByText('Passkey registered')).toBeVisible();

  // Step 2: Navigate to login
  await page.goto('https://your-app.com/login');

  // Step 3: Sign in with passkey
  await page.getByRole('button', { name: 'Sign in with Passkey' }).click();

  // The virtual authenticator uses the stored credential
  await expect(page.getByText('Welcome back')).toBeVisible();
  await expect(page).toHaveURL(/dashboard/);
});

✅ No mocking, no bypassing — you’re testing the REAL WebAuthn implementation end to end. This is the biggest advantage over traditional approaches!


♻️ Reusing Credentials Across Tests with Storage State

Registering a passkey in every test is wasteful. Use Playwright’s storage state to authenticate once and reuse:

// auth.setup.ts
import { test as setup } from '@playwright/test';

setup('register and authenticate with passkey', async ({ context, page }) => {
  await page.goto('https://your-app.com/register');
  await page.getByRole('button', { name: 'Register with Passkey' }).click();
  await expect(page.getByText('Passkey registered')).toBeVisible();

  // Save authenticated state
  await context.storageState({ path: '.auth/passkey-user.json' });
});
// playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  projects: [
    { name: 'setup', testMatch: /.*\.setup\.ts/ },
    {
      name: 'tests',
      dependencies: ['setup'],
      use: { storageState: '.auth/passkey-user.json' },
    },
  ],
});

🚨 Common Mistakes and How to Avoid Them

❌ Mistake 1: Credentials don’t persist across browser contexts.

Each browserContext has its own virtual authenticator. If your test creates a new context, previously registered passkeys won’t be available. Solution: register and login within the same context, or use storage state.

❌ Mistake 2: Not waiting for the WebAuthn ceremony to complete.

The registration and authentication ceremonies are asynchronous. Clicking the next button before the ceremony finishes causes flaky tests. Always wait for a visible confirmation element.

❌ Mistake 3: Forgetting to await credentials API calls.

context.credentials.list() returns a Promise. Missing await leads to empty results and confusing test failures.


❓ FAQ

🤔 Can I test passkeys without a real WebAuthn-enabled app?

Yes! You can use demo sites like webauthn.io to practice. For other Playwright interactions, practise on our automation practice pages.


🤔 Does Playwright’s virtual authenticator work with all browsers?

The virtual authenticator works with Chromium-based browsers. Firefox and WebKit support may vary — check the Playwright 1.61 release notes for the latest compatibility.


🤔 Can I export and import passkey credentials between test runs?

Yes, context.credentials.list() returns credential objects that can be serialized. However, using storage state (shown above) is the recommended approach for persisting authenticated sessions.


🤔 What’s the difference between passkeys and FIDO2 security keys?

Passkeys are discoverable FIDO2 credentials synced across devices (through iCloud Keychain, Google Password Manager, etc.). Hardware security keys are physical devices. Playwright’s virtual authenticator simulates both.


🤔 Do I need to modify my app’s code to test with the virtual authenticator?

No. The virtual authenticator intercepts standard WebAuthn API calls at the browser level. Your app’s code doesn’t need any changes.


🎯 Next Steps

Now that you can automate passkey testing, try these:

  • 🔧 Add passkey tests to your CI/CD pipeline
  • 🧪 Test error scenarios (expired credentials, wrong authenticator)
  • 📐 Combine passkey auth with your existing Page Object Model — see our Playwright POM tutorial
  • 💾 Explore the new page.localStorage and page.sessionStorage APIs in Playwright 1.61

🎬 Want to see this in action? Watch the full video tutorial!

Subscribe to SqaToolsByDY on YouTube for weekly QA automation tutorials

🌐 Practice on sqatools.in — free automation practice pages!

Python Polymorphism

Polymorphism means same function name, different behaviors, depending on class or input.

Two types in Python:

TypeMeaning
Compile-time (Overloading)Same function, different parameters (simulated in Python)
Runtime (Overriding)Child class modifies parent method

Each object responds differently to the same speak() call.


Python doesn’t support true overloading, so we use default parameters.


Same function → different behavior based on object type.


Child classes provide unique logic for inherited structure.


Explanation

  • Admin & Customer override the login() method.
  • Same method name → different behaviors based on object type.

FeatureWhat It DoesExample
InheritanceReuse parent class featuresclass B(A)
Multiple InheritanceChild from multiple parentsclass C(A,B)
PolymorphismSame method, different behaviorOverriding
OverridingModify parent methodRedefine in child
OverloadingSame name, different argumentsDefault parameters

Python Inheritance

Inheritance allows a class (child) to acquire properties and methods of another class (parent).

This promotes:

  • Code reusability
  • Hierarchy / structure
  • Cleaner and scalable programs

Explanation

  • Animal is the parent/base class.
  • Dog is the child/derived class.
  • Dog gets the speak() method without writing it again.

📝 Child gets access to both:
➡ show() (from Parent)
➡ display() (its own)


📝 Chain of inheritance: A → B → C
Class C inherits everything.


📝 Child receives methods of both parents.


📝 One parent → Multiple children.


📝 super() is used to call parent methods/constructors.

Python Generators

Python Tutorial › Functions › Generators

Python Generators

IntermediateLesson 29 of 4710 min read8 runnable examples

A generator is a function that produces a sequence of values lazily, one at a time, using yield. Generators make iterators easy to write and let you process huge or endless data without loading it all into memory.

In this lesson
  • Write generator functions with yield
  • Understand how a generator pauses and resumes
  • Use generator expressions
  • Chain generators into pipelines

Your first generator

A function that contains yield is a generator function. Calling it does not run the body; it returns a generator object. Each next() runs the body until the next yield.

Python
def countdown(n):    while n > 0:        yield n        n -= 1 gen = countdown(3)print(gen)print(next(gen), next(gen), next(gen))print(list(countdown(5)))
Output
<generator object countdown at 0x000001D0A798A800>
3 2 1
[5, 4, 3, 2, 1]

Compare with the iterator class in the Iterators lesson: the same behaviour in four lines.

yield pauses, it does not end

return ends a function. yield hands out a value and pauses, keeping all local variables, until the next request.

Python
def steps():    print("start")    yield 1    print("after first yield")    yield 2    print("finished") for value in steps():    print("got", value)
Output
start
got 1
after first yield
got 2
finished

Why generators save memory

A list holds every item at once. A generator holds only its current state.

Python
import sys numbers_list = [n * n for n in range(1_000_000)]numbers_gen = (n * n for n in range(1_000_000)) print(sys.getsizeof(numbers_list) > 1_000_000)print(sys.getsizeof(numbers_gen) < 1_000)print(sum(numbers_gen))
Output
True
True
333332833333500000
Note

The exact byte sizes depend on the Python version, which is why the example prints comparisons. The list needs megabytes; the generator needs a few hundred bytes whatever the range.

Generator expressions

Round brackets around a comprehension make a generator expression. When it is the only argument to a function, you can drop the extra brackets:

Python
words = ["python", "generators", "save", "memory"]print(max(len(w) for w in words))print(any(w.startswith("g") for w in words))lengths = (len(w) for w in words)print(next(lengths), list(lengths))
Output
10
True
6 [10, 4, 6]

Infinite generators

Because values are produced on demand, a generator can run forever. Take only what you need:

Python
def fibonacci():    a, b = 0, 1    while True:        yield a        a, b = b, a + b fib = fibonacci()print([next(fib) for _ in range(10)])
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Generator pipelines

Chain generators so each one processes the output of the previous one. Only one item flows through the pipeline at a time, which is how large log files are processed efficiently.

Python
log_lines = [    "INFO start",    "ERROR db timeout",    "INFO request ok",    "ERROR disk full",] def errors(lines):    for line in lines:        if line.startswith("ERROR"):            yield line def messages(lines):    for line in lines:        yield line.split(" ", 1)[1] for msg in messages(errors(log_lines)):    print(msg)
Output
db timeout
disk full

yield from

yield from hands out every item of another iterable, which is perfect for recursive generators:

Python
def flatten(items):    for item in items:        if isinstance(item, list):            yield from flatten(item)        else:            yield item print(list(flatten([1, [2, [3, 4]], 5])))
Output
[1, 2, 3, 4, 5]

Generators are single-use

Python
gen = (x for x in range(3))print(list(gen))print(list(gen))
Output
[0, 1, 2]
[]

Call the generator function again (or rebuild the expression) when you need the values a second time.

Check your understanding

Predict the output

def g():    for i in range(3):        yield i * 10    yield "done" it = g()print(next(it), next(it), list(it))

Quick quiz

1. What does calling a generator function return?

2. What happens to local variables at a yield?

3. Which creates a generator expression?

Exercise: read in chunks

Write a generator chunks(items, size) that yields lists of size items, with a shorter final chunk if needed.

Input
chunks(list(range(1, 11)), 4)
Expected output
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10]
Hint 1

Loop with range(0, len(items), size) and yield a slice.

Program Practice

20 Python Iterator & Generator Programs

Every program has a step-by-step explanation, colour-coded code and its real output.

Start practising →
Related sets:All practice sets

Python generators FAQ

What is the difference between yield and return?

return sends back one value and ends the function. yield sends back a value and pauses, so the function can continue and yield more values later.

When should I use a generator instead of a list?

When the data is large, endless, or only needed once in order, such as reading a big file line by line or streaming API results.

Can a generator be reused?

No. Once exhausted it stays empty. Call the generator function again to get a fresh one.

Python Decorators

Python Tutorial › Functions › Decorators

Python Decorators

AdvancedLesson 30 of 4712 min read7 runnable examples

A decorator adds behaviour to a function without changing its code: logging, timing, retrying, checking permissions. You meet decorators everywhere in test frameworks, such as @pytest.fixture and @pytest.mark.parametrize. This lesson builds one from scratch.

In this lesson
  • Why decorators work: functions are objects
  • Write a wrapper and apply it with @
  • Keep the function’s name with functools.wraps
  • Write decorators that take arguments

Functions are objects

A decorator relies on two facts: a function can be passed to another function, and a function can create and return a new function.

Python
def shout(text):    return text.upper() def call_twice(func, value):    return func(value), func(value) print(call_twice(shout, "hi"))
Output
('HI', 'HI')

A decorator by hand

A decorator is a function that takes a function and returns a new function, usually a wrapper that runs extra code around the original:

Python
def log_calls(func):    def wrapper(*args, **kwargs):        print(f"calling {func.__name__} with {args}")        result = func(*args, **kwargs)        print(f"{func.__name__} returned {result}")        return result    return wrapper def add(a, b):    return a + b add = log_calls(add)      # replace add with the wrapped versionadd(2, 3)
Output
calling add with (2, 3)
add returned 5

The @ syntax

@log_calls above a definition is a shortcut for add = log_calls(add):

Python
def log_calls(func):    def wrapper(*args, **kwargs):        print(f"calling {func.__name__}{args}")        return func(*args, **kwargs)    return wrapper @log_callsdef multiply(a, b):    return a * b print(multiply(4, 5))
Output
calling multiply(4, 5)
20
Note

The wrapper uses *args, **kwargs so it can pass along whatever arguments the decorated function takes.

Keep the original name with functools.wraps

Without help, the decorated function reports the wrapper’s name and loses its docstring. functools.wraps copies them over:

Python
from functools import wraps def plain(func):    def wrapper(*args, **kwargs):        return func(*args, **kwargs)    return wrapper def proper(func):    @wraps(func)    def wrapper(*args, **kwargs):        return func(*args, **kwargs)    return wrapper @plaindef first():    """First docstring.""" @properdef second():    """Second docstring.""" print(first.__name__, first.__doc__)print(second.__name__, second.__doc__)
Output
wrapper None
second Second docstring.

Always use @wraps in your decorators.

A timing decorator

Python
import timefrom functools import wraps def timer(func):    @wraps(func)    def wrapper(*args, **kwargs):        start = time.perf_counter()        result = func(*args, **kwargs)        elapsed = time.perf_counter() - start        print(f"{func.__name__} took {'under' if elapsed < 0.5 else 'over'} 0.5 s")        return result    return wrapper @timerdef slow_sum(n):    time.sleep(0.1)    return sum(range(n)) print(slow_sum(1000))
Output
slow_sum took under 0.5 s
499500

Decorators with arguments

To pass settings such as @retry(times=3), add one more outer function. retry(times=3) runs first and returns the actual decorator.

Python
from functools import wraps def retry(times):    def decorator(func):        @wraps(func)        def wrapper(*args, **kwargs):            for attempt in range(1, times + 1):                try:                    return func(*args, **kwargs)                except ValueError as e:                    print(f"attempt {attempt} failed: {e}")            raise RuntimeError(f"{func.__name__} failed {times} times")        return wrapper    return decorator calls = {"n": 0} @retry(times=3)def flaky():    calls["n"] += 1    if calls["n"] < 3:        raise ValueError("server busy")    return "success" print(flaky())
Output
attempt 1 failed: server busy
attempt 2 failed: server busy
success

Stacking decorators

Several decorators apply from the bottom up: the one closest to the function wraps it first.

Python
def bold(func):    return lambda: "<b>" + func() + "</b>" def italic(func):    return lambda: "<i>" + func() + "</i>" @bold@italicdef label():    return "Python" print(label())
Output
<b><i>Python</i></b>

Built-in decorators you will meet

DecoratorWhat it does
@staticmethod, @classmethodMethods that do not need an instance (see Classes & Objects)
@propertyCall a method like an attribute
@functools.lru_cacheRemember results of expensive calls
@dataclasses.dataclassGenerate __init__, __repr__ and more for a class
@pytest.fixture, @pytest.mark.parametrizeSet up test data and run a test with many inputs

Check your understanding

Predict the output

def twice(func):    def wrapper(x):        return func(func(x))    return wrapper @twicedef add3(x):    return x + 3 print(add3(10))

Quick quiz

1. What is @deco above def f(): equivalent to?

2. Why use functools.wraps?

3. With @a above @b above def f, which wraps f first?

Exercise: count calls

Write a decorator count_calls that counts how many times a function has been called and stores the number in wrapper.calls.

Input
call greet("Asha"), greet("Ravi"), then print greet.calls
Expected output
Hello Asha
Hello Ravi
calls: 2
Hint 1

Set wrapper.calls = 0 before returning the wrapper, and add 1 inside it.

Program Practice

Python decorators FAQ

What is a decorator in Python?

A decorator is a function that takes another function and returns a modified version of it, usually a wrapper that adds behaviour before or after the original runs.

What does functools.wraps do?

It copies the wrapped function’s name, docstring and other metadata onto the wrapper, so debugging and documentation tools see the original function.

Can a decorator take arguments?

Yes. Write a function that takes the arguments and returns the decorator, giving three levels: def retry(times): def decorator(func): def wrapper(...).

Python OS Module

Python Tutorial › Modules › OS Module

Python OS Module

IntermediateLesson 38 of 4712 min read8 runnable examples

The os module lets your program work with the operating system: create and list folders, build file paths that work on every OS, rename and delete files, and read environment variables. Its modern partner, pathlib, does the same jobs with path objects.

In this lesson
  • Create, list and remove folders
  • Build portable paths with os.path and pathlib
  • Walk a whole folder tree
  • Read environment variables

The current folder

Relative paths are resolved against the current working directory, the folder the program was started from.

Python
import os print(os.path.basename(os.getcwd()))print(os.name)        # 'nt' on Windows, 'posix' on macOS and Linux
Output
os
nt
Note

The examples on this page were run on Windows, so paths print with \. On macOS and Linux you will see / instead. The code is the same.

Create folders and files

Python
import os os.makedirs("reports/2026/nov", exist_ok=True)   # creates every missing levelwith open("reports/2026/nov/summary.txt", "w") as f:    f.write("all tests passed")with open("reports/readme.md", "w") as f:    f.write("# Reports") print(os.listdir("reports"))print(os.path.exists("reports/2026/nov/summary.txt"))
Output
['2026', 'readme.md']
True

exist_ok=True stops makedirs from raising an error when the folder already exists.

Check what a path is

Python
import os for p in ["reports", "reports/readme.md", "missing.txt"]:    print(p, os.path.exists(p), os.path.isdir(p), os.path.isfile(p)) print(os.path.getsize("reports/readme.md"), "bytes")
Output
reports True True False
reports/readme.md True False True
missing.txt False False False
9 bytes

Build and split paths

Never glue paths together with + "/". os.path.join uses the right separator for the OS:

Python
import os path = os.path.join("reports", "2026", "nov", "summary.txt")print(path)print(os.path.dirname(path))print(os.path.basename(path))print(os.path.splitext(path))
Output
reports\2026\nov\summary.txt
reports\2026\nov
summary.txt
('reports\\2026\\nov\\summary', '.txt')

Walk a folder tree

os.walk() visits every folder under a starting point and gives you its files:

Python
import os for folder, subfolders, files in os.walk("reports"):    level = folder.count(os.sep)    print("  " * level + os.path.basename(folder) + "/")    for name in files:        print("  " * (level + 1) + name)
Output
reports/
  readme.md
  2026/
    nov/
      summary.txt

Rename, move and delete

Python
import os, shutil os.rename("reports/readme.md", "reports/README.md")print(sorted(os.listdir("reports"))) os.remove("reports/README.md")             # delete a fileshutil.rmtree("reports/2026")              # delete a folder and everything in itprint(os.listdir("reports"))os.rmdir("reports")                        # delete an empty folderprint(os.path.exists("reports"))
Output
['2026', 'README.md']
[]
False
Watch out

os.remove and shutil.rmtree delete permanently; there is no recycle bin. Print the path first when you build it from variables.

Environment variables

Environment variables pass settings such as API keys and base URLs to a program without hard-coding them.

Python
import os os.environ["APP_ENV"] = "staging"           # set for this processprint(os.environ["APP_ENV"])print(os.environ.get("BASE_URL", "https://sqatools.in"))   # with a defaultprint("PATH" in os.environ)
Output
staging
Home
True
Tip

Read secrets with os.environ.get("API_TOKEN") instead of writing them in your code, so they never end up in Git.

pathlib: the modern way

pathlib.Path objects join with / and have methods for most file jobs:

Python
from pathlib import Path base = Path("data")(base / "logs").mkdir(parents=True, exist_ok=True)log = base / "logs" / "run.log"log.write_text("start\nend\n") print(log.name, log.suffix, log.stem)print(log.parent.name)print(log.read_text().splitlines())print([p.name for p in base.rglob("*.log")])
Output
run.log .log run
logs
['start', 'end']
['run.log']
Taskos / os.pathpathlib
Join pathsos.path.join(a, b)Path(a) / b
Existsos.path.exists(p)p.exists()
Make foldersos.makedirs(p, exist_ok=True)p.mkdir(parents=True, exist_ok=True)
Listos.listdir(p)p.iterdir()
Read textopen(p).read()p.read_text()
Extensionos.path.splitext(p)[1]p.suffix

Check your understanding

Quick quiz

1. Which function creates nested folders in one call?

2. Why use os.path.join instead of string concatenation?

3. How do you read an environment variable safely with a default?

Exercise: group files by extension

Create a few files in a folder, then count how many files there are of each extension.

Input
a.py, b.py, notes.txt, data.csv, c.py
Expected output
.py 3
.csv 1
.txt 1
Hint 1

os.path.splitext(name)[1] gives the extension; a Counter counts them.

Program Practice

Python os module FAQ

How do I get the current directory in Python?

os.getcwd() returns it as a string; Path.cwd() returns it as a Path object.

How do I check if a file exists in Python?

os.path.exists(path) or Path(path).exists(). Use isfile() / isdir() to check the type too.

What is the difference between os and pathlib?

os and os.path work with paths as strings. pathlib (Python 3.4+) wraps paths in objects with methods and the / operator. pathlib is usually more readable for new code.

How do I delete a folder that is not empty?

Use shutil.rmtree(path). os.rmdir only removes empty folders.

Python Read/Write CSV

Python Tutorial › File Handling › Read/Write CSV

Python Read/Write CSV

BeginnerLesson 43 of 4710 min read7 runnable examples

CSV (comma-separated values) files are plain-text tables that every spreadsheet and database can export. Python’s built-in csv module reads and writes them correctly, including the tricky cases such as commas inside quoted values.

In this lesson
  • Write rows with csv.writer
  • Read rows with csv.reader
  • Use column names with DictReader and DictWriter
  • Summarise CSV data

Write a CSV file

Open the file with newline="" (the csv module handles line endings itself), then write rows as lists.

Python
import csv rows = [    ["name", "city", "score"],    ["Asha", "Pune", 91],    ["Ravi", "Delhi", 78],    ["Meena", "Mumbai, MH", 85],]with open("students.csv", "w", newline="", encoding="utf-8") as f:    writer = csv.writer(f)    writer.writerows(rows) print(open("students.csv", encoding="utf-8").read())
Output
name,city,score
Asha,Pune,91
Ravi,Delhi,78
Meena,"Mumbai, MH",85

Notice that "Mumbai, MH" was wrapped in quotes automatically, because it contains a comma.

Watch out

Without newline="", files written on Windows get an extra blank line between rows.

Read a CSV file

csv.reader returns each row as a list of strings:

Python
import csv with open("students.csv", newline="", encoding="utf-8") as f:    reader = csv.reader(f)    header = next(reader)            # first row    print(header)    for row in reader:        print(row)
Output
['name', 'city', 'score']
['Asha', 'Pune', '91']
['Ravi', 'Delhi', '78']
['Meena', 'Mumbai, MH', '85']

DictReader: rows as dictionaries

DictReader uses the header row as keys, so you can write row["score"] instead of row[2]:

Python
import csv with open("students.csv", newline="", encoding="utf-8") as f:    for row in csv.DictReader(f):        print(row["name"], "scored", row["score"])
Output
Asha scored 91
Ravi scored 78
Meena scored 85

DictWriter

Python
import csv results = [    {"test": "login", "status": "pass", "ms": 812},    {"test": "search", "status": "fail", "ms": 1530},]with open("results.csv", "w", newline="", encoding="utf-8") as f:    writer = csv.DictWriter(f, fieldnames=["test", "status", "ms"])    writer.writeheader()    writer.writerows(results) print(open("results.csv", encoding="utf-8").read().strip())
Output
test,status,ms
login,pass,812
search,fail,1530

Append rows

Python
import csv with open("results.csv", "a", newline="", encoding="utf-8") as f:    csv.writer(f).writerow(["checkout", "pass", 990]) with open("results.csv", newline="", encoding="utf-8") as f:    print(sum(1 for _ in csv.DictReader(f)), "data rows")
Output
3 data rows

Summarise CSV data

Values come back as strings, so convert them before doing maths:

Python
import csv with open("students.csv", newline="", encoding="utf-8") as f:    students = list(csv.DictReader(f)) scores = [int(s["score"]) for s in students]top = max(students, key=lambda s: int(s["score"]))print("Average:", round(sum(scores) / len(scores), 2))print("Top:", top["name"], top["score"])print("Above 80:", [s["name"] for s in students if int(s["score"]) > 80])
Output
Average: 84.67
Top: Asha 91
Above 80: ['Asha', 'Meena']

Other delimiters

Some files use ; or tabs. Pass delimiter:

Python
import csv, io data = "id;product;price\n1;Pen;10\n2;Bag;650\n"for row in csv.DictReader(io.StringIO(data), delimiter=";"):    print(row)
Output
{'id': '1', 'product': 'Pen', 'price': '10'}
{'id': '2', 'product': 'Bag', 'price': '650'}

io.StringIO turns a string into a file-like object, which is handy for testing CSV code without a real file.

Tip

For large data or heavy analysis, Pandas reads CSV in one line: pd.read_csv("students.csv"). See the Pandas lesson.

Check your understanding

Predict the output

import csv, iorows = list(csv.reader(io.StringIO('a,"b,c",d\n1,2,3\n')))print(rows, len(rows[0]))

Quick quiz

1. What type are the values csv.reader returns?

2. Why open CSV files with newline=""?

3. Which class gives each row as a dictionary keyed by the header?

Exercise: filter rows into a new file

From students.csv, write the students who scored at least 80 to toppers.csv with the same header, then print the new file.

Input
students.csv from this lesson
Expected output
name,city,score
Asha,Pune,91
Meena,"Mumbai, MH",85
Hint 1

Use DictReader to read and DictWriter with reader.fieldnames to write.

Program Practice

Python CSV FAQ

How do I read a CSV file in Python?

with open("file.csv", newline="", encoding="utf-8") as f: then for row in csv.reader(f): or csv.DictReader(f) for dictionaries.

How do I skip the header row?

Call next(reader) once before the loop, or use DictReader, which consumes the header for you.

Why do I get blank lines between rows in my CSV on Windows?

The file was opened without newline="". Add it to open() when writing CSV files.

Should I use csv or pandas?

Use csv for simple reading and writing with no extra installs. Use pandas when you need filtering, grouping, statistics or Excel export.

Python Read/Write JSON

Python Tutorial › File Handling › Read/Write JSON

Python Read/Write JSON

BeginnerLesson 42 of 4710 min read8 runnable examples

JSON is the format APIs, config files and test data use most. Python’s built-in json module converts JSON text into dictionaries and lists, and back again, in one call.

In this lesson
  • Parse JSON strings with json.loads
  • Create JSON with json.dumps
  • Read and write JSON files
  • Handle nested data and errors

JSON and Python types

JSONPython
object {}dict
array []list
string "..."str
numberint or float
true / falseTrue / False
nullNone

Parse a JSON string: loads

Python
import json text = '{"id": 7, "name": "Asha", "active": true, "skills": ["python", "sql"], "manager": null}'user = json.loads(text) print(type(user).__name__)print(user["name"], user["skills"][0], user["active"], user["manager"])
Output
dict
Asha python True None

Create a JSON string: dumps

Python
import json report = {"suite": "login", "passed": 12, "failed": 0, "ok": True, "notes": None}print(json.dumps(report))print(json.dumps(report, indent=2, sort_keys=True))
Output
{"suite": "login", "passed": 12, "failed": 0, "ok": true, "notes": null}
{
  "failed": 0,
  "notes": null,
  "ok": true,
  "passed": 12,
  "suite": "login"
}
Note

ensure_ascii=False keeps non-English characters readable instead of \u escapes: json.dumps({"city": "Pune"}, ensure_ascii=False).

Write a JSON file: dump

dump (without the s) writes straight to a file:

Python
import json config = {    "base_url": "https://sqatools.in",    "browsers": ["chromium", "firefox"],    "timeouts": {"page": 30, "api": 10},}with open("config.json", "w", encoding="utf-8") as f:    json.dump(config, f, indent=2) print(open("config.json", encoding="utf-8").read())
Output
{
  "base_url": "https://sqatools.in",
  "browsers": [
    "chromium",
    "firefox"
  ],
  "timeouts": {
    "page": 30,
    "api": 10
  }
}

Read a JSON file: load

Python
import json with open("config.json", encoding="utf-8") as f:    config = json.load(f) print(config["timeouts"]["api"])for browser in config["browsers"]:    print("run on", browser)
Output
10
run on chromium
run on firefox
Tip

Remember the pairs: loads / dumps work with strings, load / dump work with files.

Work with nested API data

Python
import json response = json.loads("""{"page": 1, "data": [    {"id": 1, "email": "asha@example.com", "orders": [120, 80]},    {"id": 2, "email": "ravi@example.com", "orders": []},    {"id": 3, "email": "meena@example.com", "orders": [300]}]}""") for user in response["data"]:    total = sum(user["orders"])    print(f'{user["id"]} {user["email"]:<20} {total}') print([u["email"] for u in response["data"] if u["orders"]])print(response.get("next_page", "no more pages"))
Output
1 asha@example.com     200
2 ravi@example.com     0
3 meena@example.com    300
['asha@example.com', 'meena@example.com']
no more pages

Update a JSON file

Read, change, write back:

Python
import json with open("config.json", encoding="utf-8") as f:    config = json.load(f) config["browsers"].append("webkit")config["timeouts"]["page"] = 45 with open("config.json", "w", encoding="utf-8") as f:    json.dump(config, f, indent=2) print(json.load(open("config.json", encoding="utf-8"))["browsers"])
Output
['chromium', 'firefox', 'webkit']

Invalid JSON

JSON is stricter than Python: keys need double quotes and trailing commas are not allowed.

Python
import json for text in ['{"ok": true}', "{'ok': true}", '{"a": 1,}']:    try:        print(json.loads(text))    except json.JSONDecodeError as e:        print("invalid:", e.msg, "at position", e.pos)
Output
{'ok': True}
invalid: Expecting property name enclosed in double quotes at position 1
invalid: Illegal trailing comma before end of object at position 7

Custom objects

json.dumps only knows the basic types. Convert other objects first, for example with default=:

Python
import jsonfrom datetime import date order = {"id": 99, "placed": date(2026, 11, 2), "tags": {"gift"}} def to_json(value):    if isinstance(value, date):        return value.isoformat()    if isinstance(value, set):        return sorted(value)    raise TypeError(f"cannot serialise {type(value).__name__}") print(json.dumps(order, default=to_json))
Output
{"id": 99, "placed": "2026-11-02", "tags": ["gift"]}

Check your understanding

Predict the output

import jsondata = json.loads('[1, "two", null, true, {"k": 3.5}]')print(data, json.dumps(data))

Quick quiz

1. Which function parses a JSON string into Python objects?

2. What does JSON null become in Python?

3. Which makes the output easy to read with line breaks?

Exercise: summarise test results

Parse the JSON results, print the pass percentage and the names of failed tests.

Input
'[{"name": "login", "status": "pass"}, {"name": "search", "status": "fail"}, {"name": "cart", "status": "pass"}, {"name": "pay", "status": "fail"}]'
Expected output
Pass rate: 50%
Failed: search, pay
Hint 1

Count with a comprehension: [r for r in results if r["status"] == "pass"].

Program Practice

Python JSON FAQ

How do I read a JSON file in Python?

with open("data.json", encoding="utf-8") as f: data = json.load(f).

What is the difference between json.load and json.loads?

json.load reads from a file object; json.loads parses a string.

How do I pretty print JSON in Python?

print(json.dumps(data, indent=2)). Add sort_keys=True to sort the keys.

Why does json.dumps fail with “Object of type datetime is not JSON serializable”?

JSON has no date type. Convert dates to strings (isoformat()) or pass a default= function to dumps.

Python Read/Write Excel

Python Tutorial › File Handling › Read/Write Excel

Python Read/Write Excel

IntermediateLesson 44 of 4711 min read7 runnable examples

Excel workbooks hold a lot of business and test data. The openpyxl library reads and writes .xlsx files cell by cell, and pandas can load a whole sheet into a table in one line.

In this lesson
  • Create a workbook and write rows
  • Read cells, rows and ranges
  • Add formulas, styles and column widths
  • Load sheets with pandas

Install openpyxl

openpyxl is not part of the standard library. Install it with pip:

Terminal
python -m pip install openpyxl
Note

The Try it button runs Python in your browser, where openpyxl may not be available. Run these examples on your computer after installing it.

Create a workbook and write data

Python
from openpyxl import Workbook wb = Workbook()ws = wb.activews.title = "Results" ws.append(["Test", "Status", "Duration (s)"])ws.append(["login", "pass", 1.8])ws.append(["search", "fail", 3.2])ws.append(["checkout", "pass", 2.4])ws["E1"] = "Generated by Python" wb.save("results.xlsx")print("saved", ws.max_row, "rows and", ws.max_column, "columns")
Output
saved 4 rows and 5 columns

Read a workbook

Python
from openpyxl import load_workbook wb = load_workbook("results.xlsx")print(wb.sheetnames)ws = wb["Results"] print(ws["A2"].value, ws.cell(row=2, column=2).value)for row in ws.iter_rows(min_row=2, max_col=3, values_only=True):    print(row)
Output
['Results']
login pass
('login', 'pass', 1.8)
('search', 'fail', 3.2)
('checkout', 'pass', 2.4)

values_only=True returns plain values instead of cell objects, which is what you want most of the time.

Read rows as dictionaries

Python
from openpyxl import load_workbook ws = load_workbook("results.xlsx")["Results"]rows = ws.iter_rows(max_col=3, values_only=True)header = next(rows)records = [dict(zip(header, r)) for r in rows] print(records[1])print([r["Test"] for r in records if r["Status"] == "fail"])
Output
{'Test': 'search', 'Status': 'fail', 'Duration (s)': 3.2}
['search']

Update cells and add formulas

Python
from openpyxl import load_workbook wb = load_workbook("results.xlsx")ws = wb["Results"] ws["B3"] = "pass"                         # fix a valuews["C6"] = "=SUM(C2:C4)"                  # a formula, calculated when Excel opens itws["B6"] = "Total"wb.save("results.xlsx") print(load_workbook("results.xlsx")["Results"]["C6"].value)
Output
=SUM(C2:C4)
Note

openpyxl stores formulas but does not calculate them. Excel (or LibreOffice) calculates the result when it opens the file. Load with data_only=True to read the last values Excel saved.

Styles and column widths

Python
from openpyxl import load_workbookfrom openpyxl.styles import Font, PatternFill wb = load_workbook("results.xlsx")ws = wb["Results"] for cell in ws[1]:    cell.font = Font(bold=True, color="FFFFFF")    cell.fill = PatternFill("solid", fgColor="0B7F62")ws.column_dimensions["A"].width = 14 for row in ws.iter_rows(min_row=2, max_row=4):    if row[1].value == "fail":        row[1].font = Font(color="C23A3A", bold=True) wb.save("results.xlsx")print(ws["A1"].font.bold, ws.column_dimensions["A"].width)
Output
True 14.0

Several sheets

Python
from openpyxl import load_workbook wb = load_workbook("results.xlsx")summary = wb.create_sheet("Summary")summary.append(["Total tests", 3])wb.save("results.xlsx")print(load_workbook("results.xlsx").sheetnames)
Output
['Results', 'Summary']

Excel with pandas

pandas uses openpyxl under the hood and loads a whole sheet into a DataFrame:

Python
import pandas as pd df = pd.read_excel("results.xlsx", sheet_name="Results", usecols="A:C", nrows=3)print(df)print(df["Duration (s)"].mean()) df.to_excel("copy.xlsx", index=False)print(pd.read_excel("copy.xlsx").shape)
Output
       Test Status  Duration (s)
0     login   pass           1.8
1    search   pass           3.2
2  checkout   pass           2.4
2.466666666666667
(3, 3)

Check your understanding

Quick quiz

1. Which method adds a row after the last used row?

2. What does values_only=True do in iter_rows?

3. Does openpyxl calculate formulas?

Exercise: pass rate per status

Read results.xlsx and print how many tests have each status.

Input
the Results sheet created in this lesson
Expected output
pass 3
Hint 1

Loop over iter_rows(min_row=2, max_row=4, values_only=True) and count the second value.

Program Practice

Python Excel FAQ

How do I read an Excel file in Python?

Use openpyxl: load_workbook("file.xlsx")["Sheet1"], then iter_rows(values_only=True). Or use pandas: pd.read_excel("file.xlsx").

Can openpyxl read .xls files?

No. openpyxl supports .xlsx, .xlsm, .xltx and .xltm. Convert old .xls files to .xlsx first.

How do I write data to a specific cell?

Assign to it: ws["B2"] = "pass" or ws.cell(row=2, column=2, value="pass"), then wb.save().

Variables Scope In Python

Variables declared inside a function are local to that function.


Variable declared outside a function can be accessed anywhere.


Use the global keyword to change it.


Inner function can access variable from the outer function.


The nonlocal keyword allows modifying a variable in the outer (enclosing) function.