[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:
- 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. - Prompts the user to enter their name and stores it in the
name
variable. - Prompts the user to enter their phone number and stores it in the
phno
variable. - Creates a string by concatenating the name, a comma (“,”), the phone number, and a newline character (“\n”).
- Writes the created string to the opened file using the
write
method. - Closes the file (implicitly done when the
file
variable goes out of scope).
Step-by-step Explanation:
file = open("contacts.csv", "a")
– This line opens the file namedcontacts.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.name = input("Please enter name.")
– This line prompts the user to enter a name and assigns the input value to the variablename
.phno = input("Please enter phone number.")
– This line prompts the user to enter a phone number and assigns the input value to the variablephno
.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 thecontacts.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.
Good work posting these questions in detail!