0
0
Selenium Pythontesting~5 mins

Reading test data from CSV in Selenium Python

Choose your learning style9 modes available
Introduction

Reading test data from CSV helps you run tests with different inputs easily. It saves time and avoids mistakes from typing data manually.

You want to test a login form with many usernames and passwords.
You need to check a search feature with different keywords.
You want to verify a form accepts various valid and invalid inputs.
You want to separate test data from test code for easier updates.
Syntax
Selenium Python
import csv

with open('data.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        # use row data here
        print(row)

Use csv.reader to read rows as lists.

Each row is a list of strings representing one line in the CSV.

Examples
This reads a CSV with two columns: username and password, then prints them.
Selenium Python
import csv

with open('users.csv', newline='') as file:
    reader = csv.reader(file)
    for username, password in reader:
        print(f"User: {username}, Pass: {password}")
Using DictReader reads CSV rows as dictionaries using header names.
Selenium Python
import csv

with open('data.csv', newline='') as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row['email'], row['age'])
Sample Program

This script reads usernames and passwords from a CSV file and prints a message for each. It shows how to use CSV data in tests.

Selenium Python
import csv

# Sample CSV content saved in 'testdata.csv':
# username,password
# alice,pass123
# bob,secret

with open('testdata.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        username = row['username']
        password = row['password']
        print(f"Testing login with {username} and {password}")
OutputSuccess
Important Notes

Always close the CSV file or use with to open it safely.

CSV files should have consistent columns and no extra spaces.

Use DictReader for clearer code with headers.

Summary

CSV files let you store test data outside your code.

Use Python's csv module to read data easily.

Reading data from CSV helps run many tests with different inputs.