[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:

  1. Prompts the user to enter a name and stores it in the name variable.
  2. Opens the “contacts.csv” file in read mode ("r").
  3. Iterates through each line in the file using a for loop.
  4. Inside the loop, it checks if the entered name is present anywhere within the current line using the in operator.
  5. If the name is found in the line, the entire line is printed.
  6. 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:

  1. name = input("Enter name :") – This line prompts the user to enter a name and assigns the input value to the variable name.
  2. file = open("contacts.csv", "r") – This line opens the contacts.csv file in read mode (“r”) to read its contents.
  3. for line in file: – This line starts a loop that iterates through each line in the contacts.csv file.
  4. 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 (,).
"Spread the light within, illuminate the hearts around you. Sharing is not just an action, but a sacred journey of connecting souls."~ Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *

One Comment