Python Practical Assignment 7.1

Write a Python Program to Read & Print First 5 Characters of a File

Introduction

In Python, we can read a specific number of characters from a file using the read() method. By passing a number inside read(), we can control how many characters to display.


Logic to Write the Code

  1. Start the program.
  2. Open the file in read mode ("r").
  3. Use read(5) to read the first 5 characters.
  4. Print the content without adding any separator.
  5. Close the file.
  6. End the program.

Source Code (Beginner Friendly)

# Python program to read and print first 5 characters of a file

# Opening the file in read mode
file = open("sample.txt", "r")

# Reading first 5 characters
content = file.read(5)

# Printing the content (no separator added)
print(content)

# Closing the file
file.close()

Sample Output

If sample.txt contains:

Hello Students

Output:

Hello

Viva Questions with Answers

1. What does read(5) do?

It reads the first 5 characters from the file.

2. What is the default mode of open()?

The default mode is read mode "r".

3. What happens if the file has less than 5 characters?

It will print all available characters without error.

4. Why do we close the file?

To release system resources.

5. Can we read more than 5 characters?

Yes, by changing the number inside read().

Spread the love

Leave a Comment

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

Scroll to Top