CBSE Class 12 Computer Science Question 108 of 145

File Handling — Question 4

Back to all questions
4
Question

Question 4

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) 
Output
Name: Kumar     Phone: 8574075846
Name: Priya     Phone: 5873472904
Name: Neetu     Phone: 7897656378