Python Practical Assignment 6.1

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

  1. Start the program.
  2. Open the file using open() in read mode ("r").
  3. Read the file content using read().
  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 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.


Spread the love

Leave a Comment

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

Scroll to Top