[Type B] File Handling – Chapter 5 Sumita Arora

|
Table of Contents

4. Write code to open file contacts.txt with shown information and print it in following form:

Name: <name>		Phone: <phone number>

Answer: Let’s assume the contents of the file contacts.txt as below. Here, full name and phone number are separated by a space.

contacts.txt file contents:

Python
# Open the contacts.txt file in read mode
with open('contacts.txt', 'r') as file:
    # Iterate through each line in the file
    for line in file:
        # Split the line into a list of words
        words = line.strip().split(' ')
        
        # Extract the name and phone number from the list
        name = ' '.join(words[:-1])
        phone_number = words[-1]
        
        # Print the name and phone number in the desired format
        print(f'Name: {name}\tPhone: {phone_number}')
Output
Name: John Doe	Phone: 555-1234
Name: Jane Smith	Phone: 555-5678
Name: Bob Johnson	Phone: 555-9012

Here’s a brief explanation of the code:

  1. The open() function is used to open the contacts.txt file in read mode ('r').
  2. The with statement is used to ensure that the file is properly closed after it is no longer needed.
  3. The for loop is used to iterate through each line in the file.
  4. The strip() method is used to remove any leading or trailing whitespace from the line.
  5. The split() method is used to split the line into two parts using the colon as the delimiter. The resulting list is unpacked into the name and phone_number variables.
  6. Finally, the print() function is used to print the name and phone number in the desired format. The f string is used to format the output string with the name and phone_number variables.

Detailed Explanation:

In this example, the contacts.txt file contains three lines with names and phone numbers separated by a space. The Python script opens the file in read mode, iterates through each line, splits the line into a list of words using the split() method, and extracts the name and phone number from the list.

To extract the name, we use the join() method to concatenate all the words in the list except for the last one, which is the phone number. To extract the phone number, we simply select the last element of the list using the index -1.

Finally, we print the name and phone number in the desired format using the print() function with an f-string. The output shows the name and phone number for each contact in the file.

An alternate approach to the code would be easy when there’s a colon or comma or other symbol to split against other than a space. Splitting through a space also splits through the full name along with the phone number. The approach works if contacts.txt contains:

Python
# Open the contacts.txt file in read mode
with open('contacts.txt', 'r') as file:
    # Iterate through each line in the file
    for line in file:
        # Split the line using the colon as the delimiter
        name, phone_number = line.strip().split(':')
        
        # Print the name and phone number in the desired format
        print(f'Name: {name}\tPhone: {phone_number}')

In this example, we don’t need to use join or list traversing. The Python script opens the file in read mode, iterates through each line, splits the line using the colon as the delimiter, and prints the name and phone number in the desired format. The output is the same.

"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