Computer Science
What is the following code doing ?
file = open("contacts.csv", "a")
name = input("Please enter name.")
phno = input("Please enter phone number.")
file.write(name + "," + phno + "\n")
Python File Handling
3 Likes
Answer
This code opens a CSV file named contacts.csv
in append mode, as indicated by the mode "a". This mode allows new data to be added to the end of the file without overwriting existing content. It then prompts the user to enter a name and a phone number through the console using the input()
function. After receiving input, it concatenates the name and phno separated by a comma, and appends a newline character '\n' to signify the end of the line. Finally, it writes this concatenated string to the CSV file using the write()
method of the file object. This operation effectively adds a new record to the CSV file with the provided name and phone number.
Answered By
3 Likes
Related Questions
Write code to open file contacts.txt with shown information and print it in following form :
Name: <name> Phone: <phone number>
Consider the file "poemBTH.txt" and predict the outputs of following code fragments if the file has been opened in filepointer file1 with the following code :
file1 = open("E:\\mydata\\poemBTH.txt", "r+")
(a)
print("A. Output 1") print(file1.read()) print()
(b)
print("B. Output 2") print(file1.readline()) print()
(c)
print("C. Output 3") print(file1.read(9)) print()
(d)
print("D. Output 4") print(file1.readline(9))
(e)
print("E. Output of Readlines function is") print(file1.readlines()) print()
NOTE. Consider the code fragments in succession, i.e., code (b) follows code (a), which means changes by code (a) remain intact when code (b) is executing. Similarly, code (c) follows (a) and (b), and so on.
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)
Consider the file poemBTH.txt and predict the output of following code fragment. What exactly is the following code fragment doing ?
f = open("poemBTH.txt", "r") nl = 0 for line in f: nl += 1 print(nl)