[Type B] File Handling – Chapter 5 Sumita Arora

|
Table of Contents

6. What is following code doing?

Python
file = open("contacts.csv", "a")
name = input("Please enter name.")
phno = input("Please enter phone number.")
file.write (name + "," + phno + "\n")

Answer: The code creates a file named “contacts.csv” in append mode ("a"), prompts the user for name and phone number, and then writes them to the file in a comma-separated format, followed by a newline character. Here’s a step-by-step explanation of the code:

Explanation:

  1. Opens the file “contacts.csv” in append mode ("a"). This mode creates the file if it doesn’t exist or opens it for appending new data if it exists.
  2. Prompts the user to enter their name and stores it in the name variable.
  3. Prompts the user to enter their phone number and stores it in the phno variable.
  4. Creates a string by concatenating the name, a comma (“,”), the phone number, and a newline character (“\n”).
  5. Writes the created string to the opened file using the write method.
  6. Closes the file (implicitly done when the file variable goes out of scope).

Step-by-step Explanation:

  1. file = open("contacts.csv", "a") – This line opens the file named contacts.csv in append mode (“a”). If the file doesn’t exist, it will be created. Appending to a file allows you to add content to the end of the file without deleting the existing data.
  2. name = input("Please enter name.") – This line prompts the user to enter a name and assigns the input value to the variable name.
  3. phno = input("Please enter phone number.") – This line prompts the user to enter a phone number and assigns the input value to the variable phno.
  4. file.write (name + "," + phno + "\n") – This line writes the user-entered name, a comma as a separator, the phone number, and a newline character (\n) to the contacts.csv file. This action creates a new line with the entered name and phone number, formatted as a CSV row.

It is important to note that this code does not close the file after writing to it. To ensure that files are properly closed and resources are freed, it’s a good practice to use the with statement, like so:

Python
with open("contacts.csv", "a") as file:
    name = input("Please enter name.")
    phno = input("Please enter phone number.")
    file.write(f"{name},{phno}\n")

Using the with statement automatically closes the file after the nested block of code has been executed.

"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