[Type B] File Handling – Chapter 5 Sumita Arora
Table of Contents
7. Consider the file “contacts.csv” created in above Q. and figure out what the following code is trying to do?
Python
name = input("Enter name :")
file = open("contacts.csv", "r")
for line in file:
if name in line:
print (line)
Answer: The code prompts the user for a name, opens the “contacts.csv” file in read mode ("r"
), iterates through each line, and prints any line containing the entered name.
Explanation:
- Prompts the user to enter a name and stores it in the
name
variable. - Opens the “contacts.csv” file in read mode (
"r"
). - Iterates through each line in the file using a
for
loop. - Inside the loop, it checks if the entered
name
is present anywhere within the current line using thein
operator. - If the name is found in the line, the entire line is printed.
- The loop continues, checking each line in the file.
Step-by-step Explanation:
The given code snippet searches the contacts.csv
file for a specific name provided by the user through the input prompt and then prints the corresponding line if the name is found in the file. Here’s a step-by-step explanation of the code:
name = input("Enter name :")
– This line prompts the user to enter a name and assigns the input value to the variablename
.file = open("contacts.csv", "r")
– This line opens thecontacts.csv
file in read mode (“r”) to read its contents.for line in file:
– This line starts a loop that iterates through each line in thecontacts.csv
file.if name in line:
– This line checks if the entered name is present in the current line. Since the file is in CSV format, it searches for the name within each line, which contains a name and a phone number separated by a comma (,
).
Good work posting these questions in detail!