[Type B] File Handling – Chapter 5 Sumita Arora
Table of Contents
10. Write a method in python to read the content from a text file diary.txt line by line and display the same on screen.
Answer: Here’s a method to read content line by line and display it in Python:
Python
def read_file(file_name):
try:
with open(file_name, "r") as file:
for line in file:
print(line, end="")
except FileNotFoundError:
print(f"Error: File '{file_name}' not found.")
# Example usage
read_file("diary.txt")
Explanation:
- Function Definition: The code defines a function
read_file_line_by_line
that takes a filename as input. - Error Handling: It utilizes a
try-except
block to handle potential file access errors (if the file is not found). - File Opening: Inside the
try
block, it opens the file in read mode ("r"
) using thewith
statement. - Reading and Printing: It iterates through each line in the file using a
for
loop and prints each line with theprint
statement. An empty string (""
) in the print avoids adding extra newlines.
Good work posting these questions in detail!