KnowledgeBoat Logo

Computer Science

Consider the file "contacts.csv" created in above Q. 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)

Python File Handling

3 Likes

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.

Answered By

2 Likes


Related Questions