“Create a CSV file by entering user id and password, read and search the password for a given user id” is a very common Class 12 computer science practical. You write the records into a CSV file with csv.writer, read them back with csv.reader and search for the user id. In this post you will get the complete program, the same program with csv.DictReader, a row-by-row dry run, ways to add more users and to use a function, common mistakes with real outputs, practice questions and an FAQ. Use the interactive tool below to try your own users.
Write user ids and passwords into a CSV file, then read the file and search the password for a user id.
Graphical view
Python code
Output
What You Will Learn
- The problem statement
- What a CSV file is and how Python writes and reads it
- The program
- Dry run
- Other ways: DictReader, append and function
- Common mistakes, practice questions and FAQ
Problem Statement
Create a CSV file by entering user id and password, read and search the password for a given user id.
The program asks for the number of users, then the user id and password of each one, and saves them in users.csv. After that it reads the file, asks for a user id and prints the password of that user. If the user id is not in the file, it prints User id not found. The interactive tool above accepts 1 to 5 users. A user id can have up to 10 letters and digits, and a password up to 10 characters.
What a CSV File Is and How Python Writes and Reads It
CSV stands for Comma Separated Values. It is a plain text file. Each line is one record, and the values in a line are separated by commas. For our program the file looks like this:
amit,pass123
riya,hello@1
karan,abc#9Python has a built-in csv module for these files. Only four things are needed:
| Task | Statement |
|---|---|
| Open the file for writing | f = open("users.csv", "w", newline="") |
| Make a writer | w = csv.writer(f) |
| Write one record | w.writerow([userid, password]) |
| Make a reader | r = csv.reader(f), then for row in r: gives each line as a list |
writerow() takes a list and writes it as one line, with a comma between the values. csv.reader does the opposite: it reads one line at a time and gives it back as a list of strings, so for the line riya,hello@1 we get ['riya', 'hello@1']. Then row[0] is the user id and row[1] is the password.
To search, we go through the rows one by one. If row[0] is equal to the user id we want, we print row[1] and stop. A variable found, which starts as False, remembers whether we found it. It is set to True on success, so the not found message is printed only when the whole file was read without a match.
The Program
Logic:
- Create: open
users.csvin"w"mode, make a writer, readnand for every user read the user id and password and save them withwriterow(). Close the file. - Search: open the file in
"r"mode, make a reader, read the user id to search (find) and setfound = False. - For every row, if
row[0] == find, printrow[1], setfound = Trueandbreak. - After the loop, if
foundis stillFalse, print User id not found. Close the file.
Python program
import csv
f = open("users.csv", "w", newline="")
w = csv.writer(f)
n = int(input("Enter number of users: "))
for i in range(n):
userid = input("Enter user id: ")
password = input("Enter password: ")
w.writerow([userid, password])
f.close()
f = open("users.csv", "r")
r = csv.reader(f)
find = input("Enter user id to search: ")
found = False
for row in r:
if row[0] == find:
print("Password:", row[1])
found = True
break
if found == False:
print("User id not found")
f.close()
Output 1 (user id found):
Enter number of users: 3
Enter user id: amit
Enter password: pass123
Enter user id: riya
Enter password: hello@1
Enter user id: karan
Enter password: abc#9
Enter user id to search: riya
Password: hello@1
Output 2 (user id not found):
Enter number of users: 3
Enter user id: amit
Enter password: pass123
Enter user id: riya
Enter password: hello@1
Enter user id: karan
Enter password: abc#9
Enter user id to search: sonia
User id not found
Dry Run
Take the users from Output 1 and search for riya.
| Step | row | row[0] == “riya” | Action |
|---|---|---|---|
| 1 | [‘amit’, ‘pass123’] | False | Go to the next row |
| 2 | [‘riya’, ‘hello@1’] | True | Print Password: hello@1, found = True, break |
| 3 | The loop stops. The third row is never read. found is True, so no not found message. | ||
If we search for sonia, all three comparisons are False. The loop ends by itself, found is still False and the program prints User id not found.
Other Ways
Method 2: csv.DictReader
Write a header line userid,password first. Then DictReader uses it as the column names and gives every row as a dictionary, so the code is easier to read. The header line is not given as a row.
import csv
f = open("users.csv", "w", newline="")
w = csv.writer(f)
w.writerow(["userid", "password"])
n = int(input("Enter number of users: "))
for i in range(n):
userid = input("Enter user id: ")
password = input("Enter password: ")
w.writerow([userid, password])
f.close()
f = open("users.csv", "r")
r = csv.DictReader(f)
find = input("Enter user id to search: ")
found = False
for row in r:
if row["userid"] == find:
print("Password:", row["password"])
found = True
break
if found == False:
print("User id not found")
f.close()The file now has a header line:
userid,password
amit,pass123
riya,hello@1
karan,abc#9Output (search for karan):
Enter number of users: 3
Enter user id: amit
Enter password: pass123
Enter user id: riya
Enter password: hello@1
Enter user id: karan
Enter password: abc#9
Enter user id to search: karan
Password: abc#9
Method 3: Add more users without erasing the file
Opening with "a" (append) adds rows at the end and keeps the old ones. Here we added the user sonia to the file made by Program 1.
import csv
f = open("users.csv", "a", newline="")
w = csv.writer(f)
w.writerow(["sonia", "moon#7"])
f.close()
f = open("users.csv", "r")
for row in csv.reader(f):
print(row)
f.close()Output:
['amit', 'pass123']
['riya', 'hello@1']
['karan', 'abc#9']
['sonia', 'moon#7']
Method 4: Use a function
A function that returns the password, or None if the user id is missing, can be used again and again. with open(...) closes the file by itself. This reads the file made by Program 1.
import csv
def find_password(userid):
with open("users.csv", "r") as f:
for row in csv.reader(f):
if row[0] == userid:
return row[1]
return None
p = find_password("riya")
if p is None:
print("User id not found")
else:
print("Password:", p)Output:
Password: hello@1
Common Mistakes
- Using “w” when you wanted to add:
"w"erases the file. We ran the program once with the useronlyand again with the usersecond, and the file contained onlysecond,y. Use"a"to add rows. - Forgetting f.close(): the data is still in the memory buffer. We wrote a row without closing the file and then read it: the file was empty (
''). Close the file, or usewith. - Blank lines in the file: a blank line becomes the empty list
[], androw[0]stops the program withIndexError: list index out of range. Checkif len(row) > 0first when a file may have blank lines. - Case of the letters:
Riyaandriyaare different strings. Our search forRiyaprinted User id not found. - Writing a string instead of a list:
w.writerow(userid, password)stops withTypeError: writer.writerow() takes exactly one argument (2 given)becausewriterow()takes one list. Writew.writerow([userid, password]). - Forgetting newline=””: the csv module already ends each row with
\r\n. Withoutnewline="", text mode can add one more carriage return on Windows, which shows as blank lines in Excel. - Mixing up reader and DictReader: with
DictReaderuserow["userid"], notrow[0].
Practice Questions
- Add a menu to the program with two choices: add a user and search a password.
- Make the search ignore the case of the user id.
- Let the user change the password of a user id (read all rows, change one, write all rows again).
- Count how many users are saved in the file.
- Print all the user ids whose password has more than 6 characters.
Frequently Asked Questions
What is a CSV file?
CSV means Comma Separated Values. It is a plain text file in which every line is one record and the values in the line are separated by commas, for example riya,hello@1. Excel, Google Sheets and Python can all open it.
How do you create a CSV file in Python?
Import the csv module, open the file in "w" mode with newline="", make a writer with csv.writer(f) and call w.writerow([userid, password]) for every record. Close the file at the end.
Why do we write newline=”” when opening a CSV file?
The csv module adds its own line ending (\r\n) after every row. Python’s documentation says to open the file with newline="" so that text mode does not change the line endings again, which can give blank lines between rows on Windows.
What is the difference between csv.reader and csv.DictReader?
csv.reader gives every row as a list, so you write row[0] and row[1]. csv.DictReader uses the first line as column names and gives every row as a dictionary, so you write row["userid"] and row["password"]. DictReader needs a header line in the file.
What does writerow() do?
It writes one list as one line of the file. The values are joined with commas, so w.writerow(["riya", "hello@1"]) writes riya,hello@1.
What happens if the password contains a comma?
The csv module puts quotes around the value so the file stays correct. In our test, ["amit", "a,b"] was written as amit,"a,b" and read back as the same two values.
What is the difference between “w”, “a” and “r” modes for a CSV file?
"w" creates the file and erases the old content. "a" adds new rows at the end and keeps the old rows. "r" only reads. Running Program 1 twice erases the first run, because it uses "w".
Why is the search case sensitive?
Python compares strings exactly, so "Riya" is not equal to "riya". In our test, searching Riya for a saved riya printed User id not found. Use row[0].lower() == find.lower() if you want to ignore the case.
Why do we use break after finding the user id?
Once the user id is found there is no need to read the remaining rows, so break stops the loop. The flag found tells the program afterwards whether the search succeeded, so the not found message is printed only when it did not.
Is it safe to store passwords in a CSV file?
No. A CSV file is plain text, so anyone who opens it can read every password. This program is only a practice exercise. Real applications never store the password itself. They store a hash of it, made with a library such as hashlib or bcrypt, and compare hashes.