Write a Python Program to Read & Print File Content
Introduction
In Python, we can read data from a file using built-in functions. The open() function is used to open a file, and we can print its content using the read() method.
Logic to Write the Code
- Start the program.
- Open the file using
open()in read mode ("r"). - Read the file content using
read(). - Print the content.
- Close the file.
- End the program.
Source Code (Beginner Friendly)
# Python program to read and print file content
# Opening the file in read mode
file = open("sample.txt", "r")
# Reading the file content
content = file.read()
# Printing the content
print(content)
# Closing the file
file.close()
Sample Output
(If sample.txt contains:)
Hello Students
Welcome to Python Programming
Output:
Hello Students
Welcome to Python Programming
Viva Questions with Answers
1. Which function is used to open a file in Python?
The open() function is used to open a file.
2. What does "r" mode mean?
"r" means read mode.
3. Why do we use file.close()?
To close the file after reading and free system resources.
4. What will happen if the file does not exist?
It will give a FileNotFoundError.
5. Which method is used to read the entire file content?
The read() method is used to read the full file content.
