Python Practical Assignment 15.1

Write a Python Program to Read & Print File Content

Introduction

In Python, we can read the content of a file using the open() function. The file is opened in read mode and its content is displayed using the read() method.


Logic to Write the Code

  1. Start the program.
  2. Open the file using open() in read mode ("r").
  3. Read the content using read() method.
  4. Print the content.
  5. Close the file.
  6. 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 content of the file
data = file.read()

# Printing the content
print(data)

# Closing the file
file.close()

Sample Output

If sample.txt contains:

Welcome to Python
This is file handling example

Output:

Welcome to Python
This is file handling example

Viva Questions with Answers

1. Which function is used to open a file in Python?

The open() function.

2. What does "r" mode mean?

It means read mode.

3. Why do we use file.close()?

To close the file and free system resources.

4. What will happen if the file does not exist?

It will raise a FileNotFoundError.

5. Which method reads the entire file content?

The read() method.


Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top