CBSE Class 12 Computer Science Question 110 of 136

Data File Handling — Question 49

Back to all questions
49
Question

Question 49

Consider the file "contacts.csv" created in the question above and figure out what the following code is trying to do?

name = input("Enter name: ")
file = open("contacts.csv", "r")
for line in file: 
    if name in line: 
       print(line)
Answer

The code asks the user to enter a name. It then searches for the name in "contacts.csv" file. If found, the name and phone number are printed as the output.

Explanation
  1. name = input("Enter name :") — This line prompts the user to enter a name through the console, and the entered name is stored in the variable name.
  2. file = open("contacts.csv", "r") — This line opens the file contacts.csv in read mode and assigns the file object to the variable file.
  3. for line in file: — This line initiates a for loop that iterates over each line in the file handle (file represents the opened file object), which enables interaction with the file's content. During each iteration, the current line is stored in the variable line.
  4. if name in line: — Within the loop, it checks if the inputted name exists in the current line using the in operator.
  5. print(line) — If the name is found in the current line, this line prints the entire line to the console.