Tuesday, November 15, 2022

Files 2 - Python Programming for Beginners Practice Exercise 13

Exercise 13:

Create a program that opens file.txt. Read each line of the file and prepend it with a line number.

The contents of files.txt:

  1. This is line one.
  2. This is line two.
  3. Finally, we are on the third and last line of the file.

Sample Output:

  1. 1: This is line one.
  2. 2: This is line two.
  3. 3: Finally, we are on the third and last line of the file.

Solution:

  1. #!/usr/bin/env python3
  2.  
  3. with open('file.txt') as file:
  4. line_number = 1
  5. for line in file:
  6. print('{}: {}'.format(line_number, line.rstrip()))
  7. line_number += 1

No comments:

Post a Comment