Advertisements
Advertisements
प्रश्न
Reading a file line by line from beginning is a common task, what if you want to read a file backward. This happens when you need to read log files. Write a program to read and display content of file from end to beginning.
कोड लेखन
Advertisements
उत्तर
The file is opened in binary mode and read one byte at a time from the last position towards the beginning. This is suitable for large files because the complete file is not loaded into memory.
def display_backward(filename):
with open(filename, "rb") as file:
file.seek(0, 2)
position = file.tell() - 1
while position >= 0:
file.seek(position)
byte = file.read(1)
print(byte.decode("utf-8", errors="replace"), end="")
position -= 1
display_backward("story.txt")
This displays the characters in reverse order. For reverse line order rather than reverse character order, a temporary file or an external indexing technique is generally used.
shaalaa.com
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
