Computer Science
Write code to open file contacts.txt with shown information and print it in following form :
Name: <name> Phone: <phone number>
Answer
Let the file "contacts.txt" include following sample text:
Kumar 8574075846
Priya 5873472904
Neetu 7897656378
with open("contacts.txt", "r") as file:
for line in file:
name, phone = line.strip().split()
print("Name: " + name + " \t Phone: " + phone)
Name: Kumar Phone: 8574075846
Name: Priya Phone: 5873472904
Name: Neetu Phone: 7897656378
Related Questions
If the file 'poemBTH.txt' contains the following poem (by Paramhans Yoganand) :
God made the Earth; Man made confining countries And their fancy-frozen boundaries. But with unfound boundLess Love I behold the borderLand of my India Expanding into the World. HaiL, mother of religions, Lotus, scenic beauty, and sages!
Then what outputs will be produced by both the code fragments given in question1.
Consider the file poemBTH.txt given above (in previous question). What output will be produced by following code fragment ?
obj1 = open("poemBTH.txt", "r") s1 = obj1.readline() s2.readline(10) s3 = obj1.read(15) print(s3) print(obj1.readline()) obj1.close()
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.
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")