Computer Science
Write a program to display all the records in a file along with line/record number.
Answer
Let the file "f1.txt" include the following sample text:
Soft whispers of the wind.
A melody in the trees.
Sun-kissed petals dance.
A garden's quiet song.
file_name = 'f1.txt'
line_number = 1
f = open(file_name, 'r')
for line in f:
print("Line", line_number, ":", line.strip())
line_number += 1
f.close()
Output
Line 1 : Soft whispers of the wind.
Line 2 : A melody in the trees.
Line 3 : Sun-kissed petals dance.
Line 4 : A garden's quiet song.
Related Questions
Write a Python program to display the size of a file after removing EOL characters, leading and trailing white spaces and blank lines.
Write a function Remove_Lowercase() that accepts two file names, and copies all lines that do not start with lowercase letter from the first file into the second file.
Write a method in Python to write multiple line of text contents into a text file "mylife.txt".
Write a method in Python to read the content from a text file diary.txt line by line and display the same on screen.