ByteBoard Notes Notes

Create a CSV file of user-ids and passwords and search for the password of a given user-id

Computer Science XII · Experiment 17 of 29 · Python

★ CBSE suggested12-CSPython programs
Expt. No.17
Page No.34

CSV: user-id and password search

Aim

To write a Python program that creates a CSV file of user-ids and passwords, then reads it and searches for the password of a given user-id.

Concepts used

Algorithm

  1. create(): open users.csv in "w" mode with newline=""; write a header row, then input and write each user-id and password with writerow().
  2. search(uid): open the file, read it with csv.reader() and check each row.
  3. If the first value matches the user-id, display the password; otherwise display "not found".

Program

# CSV file of user-ids and passwords import csv def create():    n = int(input("How many users? "))    with open("users.csv", "w", newline="") as f:        w = csv.writer(f)        w.writerow(["UserID", "Password"])        for i in range(n):            uid = input("User ID : ")            pwd = input("Password: ")            w.writerow([uid, pwd]) def search(uid):    found = False    with open("users.csv", "r") as f:        r = csv.reader(f)        for row in r:            if row[0] == uid:                print("Password of", uid, "is", row[1])                found = True    if not found:        print("User ID", uid, "not found") create()search(input("Enter the user ID to search: "))

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python csv_userid_password.py
How many users? 3 User ID : arjun01 Password: pass@123 User ID : meera22 Password: m22#sql User ID : kabir_x Password: kx2026 Enter the user ID to search: meera22 Password of meera22 is m22#sql

✓ Printed by running this program, not typed by hand.

Contents of users.csv

users.csvafter the run
UserID,Password
arjun01,pass@123
meera22,m22#sql
kabir_x,kx2026

Result

users.csv was created with a header and three rows. Searching for meera22 displayed its password, m22#sql.

Viva voce: what the examiner may ask

01What does newline="" do when opening a CSV file for writing?

It stops Python adding an extra blank line between rows on Windows.

02What does csv.reader() return for each row?

A list of strings, one per value, e.g. ['meera22', 'm22#sql'].

03What is the difference between writerow() and writerows()?

writerow() writes one row (a list); writerows() writes many rows (a list of lists).

Variations for the lab test

  1. Allow the user to change a password.
  2. Display all user-ids whose password is shorter than 8 characters.
  3. Count the users in the file without counting the header.
! Common mistake Forgetting the [ ] in w.writerow(uid, pwd) raises TypeError; writerow() takes one list.
Back to the 12-CS index