How to Import Users from CSV into LDAP-like Dicts in Python

Reads a CSV of user records and converts each row into an LDAP-style dictionary with standard attributes using Python's csv module.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 15 views 0 copies

Python code

40 lines
Python 3.9+
import csv
import io
from pathlib import Path


def mock_ldap_import(csv_path):
    """
    Reads a CSV file with user data and returns a list of LDAP-like user dicts.
    Adds standard LDAP attributes that would come from directory schema.
    """
    with open(csv_path, newline="", encoding="utf-8") as csvfile:
        reader = csv.DictReader(csvfile)
        users = []
        for row in reader:
            user = {
                "uid": row["username"],
                "cn": f"{row['first_name']} {row['last_name']}",
                "mail": row["email"],
                "givenName": row["first_name"],
                "sn": row["last_name"],
                "department": row.get("department", "unknown"),
                "objectClass": ["inetOrgPerson", "organizationalPerson"],
                "enabled": row.get("enabled", "TRUE").upper() == "TRUE",
            }
            users.append(user)
        return users


if __name__ == "__main__":
    sample_csv = """username,first_name,last_name,email,department,enabled
jdoe,John,Doe,jdoe@example.com,Engineering,TRUE
asmith,Alice,Smith,asmith@example.com,Sales,TRUE
bmarley,Bob,Marley,bmarley@example.com,,FALSE
"""
    p = Path("/tmp/mock_users.csv")
    p.write_text(sample_csv)

    imported_users = mock_ldap_import(p)
    for user in imported_users:
        print(user)

Output

stdout
{'uid': 'jdoe', 'cn': 'John Doe', 'mail': 'jdoe@example.com', 'givenName': 'John', 'sn': 'Doe', 'department': 'Engineering', 'objectClass': ['inetOrgPerson', 'organizationalPerson'], 'enabled': True}
{'uid': 'asmith', 'cn': 'Alice Smith', 'mail': 'asmith@example.com', 'givenName': 'Alice', 'sn': 'Smith', 'department': 'Sales', 'objectClass': ['inetOrgPerson', 'organizationalPerson'], 'enabled': True}
{'uid': 'bmarley', 'cn': 'Bob Marley', 'mail': 'bmarley@example.com', 'givenName': 'Bob', 'sn': 'Marley', 'department': 'unknown', 'objectClass': ['inetOrgPerson', 'organizationalPerson'], 'enabled': False}

How it works

The csv.DictReader reads each row as a dictionary keyed by the header row, making it easy to map columns to LDAP attribute names like uid and cn. The get() method supplies a default value for missing columns (e.g., department defaults to 'unknown'), so the script won't crash if a field is omitted. The enabled flag is normalized to a boolean by comparing the uppercase value against 'TRUE', which handles common variants like 'true' or 'False'. Finally, objectClass is set as a list to represent multi-valued LDAP attributes.

Common mistakes

  • Calling `row["department"]` directly without `.get()` when the column may be missing or empty.
  • Forgetting to convert the CSV's `enabled` field from string to boolean, leading to incorrect logic.
  • Assuming `csv.DictReader` preserves column order, which it does not; access fields by name instead of index.
  • Opening the file without `newline="` (or not using `encoding="utf-8"`) on Windows, causing `\r` in field values.

Variations

  1. Use `pandas.read_csv` to load the CSV into a DataFrame, then convert rows to dicts with `df.to_dict('records')`.
  2. Write the parsed users to an actual LDIF file using `ldap3` for a real LDAP import.
  3. Use `csv.DictWriter` to write a cleaned CSV that includes only valid LDAP attributes.

Real-world use cases

  • Bulk-provisioning user accounts in a test LDAP server from an HR export in CSV format.
  • Migrating on-premises user data to a cloud directory service by transforming rows into LDAP-compatible schemas.
  • In a DevOps pipeline, importing team members from a spreadsheet into a sandbox directory for integration tests.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.