Python Program to Store and Search User IDs and Passwords in a CSV File
Intermediate · File handling · CBSE class 12 practical list
A CSV (comma separated values) file stores a table as plain text, one row per line with commas between the values, and it opens in any spreadsheet program. This program uses Python's csv module to save user IDs and passwords in a CSV file, then searches the file for a user ID and prints its password. It is the CSV file program in the CBSE class 12 practical list.
Program
Saved 3 users in users.csv Password for diya_k is moon#456 User ID rohan not found
How it works
writer.writerows(users)writes each inner list as one line of the file, with commas between the values.- The csv module asks for
newline=""when opening the file; without it, Windows adds an extra blank line after every row. csv.reader(f)gives back each line as a list of strings, andnext(reader)skips the header row.- When
row[0]matches the user ID, the password inrow[1]is printed andreturnends the search; if the loop finishes without a match, the not found message is printed. - Real websites should never store passwords as plain text like this (they store a scrambled form called a hash), but plain text is fine for practising file handling.
Another way to write it
Using csv.DictReader
Password for aarav01 is sun@123
csv.DictReader reads the header row by itself and gives each row as a dictionary, so you write row["password"] instead of remembering that the password is row[1].
Try it yourself
Write a function that takes a new user ID and password and adds them to the file by opening it with "a" (append) instead of "w".
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Search a Roll Number in a Binary File
- Update Marks in a Binary File
- Generate a Random Password
- Read a Text File and Separate Words with #
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Copy Lines Without the Letter 'a' to Another File
- Count the Words "Me" and "My" in a Text File
- Display Lines Starting with T in a Text File
- Count Words in a Text File
All Python programs · CBSE class 12 practical file · Python exercises