Python Tutorial in Hindi #15 - File Handling | Read Operations

Python File Handling Tutorial – Read Files Using read() and readline() | Hindi Explained


In this video by Mohit Decodes, we explore how to read data from files using Python. You’ll learn how to open text files, read content using read() and readline(), and understand the modes used in file handling like "r" and "t". Real-life examples are provided to help you apply file reading in practical scenarios like reading logs, config files, or user input.


✅ Topics Covered:

Introduction to File Handling in Python

How to Open a File

Reading Data with read(), readline(), and readlines()

File Modes: "r", "t" (Text Mode)

Best Practices for Reading Files

Real-World Examples


# ================================
# Python File Handling - Read Operations
# ================================

# Opening a file in read mode ('r')
# Make sure "demo.txt" exists in your folder before running this code.
file = open("demo.txt", "r")

# 1️⃣ Read the entire file content at once
print("----- Using read() -----")
content = file.read()
print(content)

# After reading, the file pointer moves to the end.
# So further reads will return an empty string unless we reset it.

# Reset file pointer to the beginning using seek(0)
file.seek(0)

# 2️⃣ Read line by line using readline()
print("----- Using readline() -----")
line1 = file.readline()
print("Line 1:", line1.strip())

line2 = file.readline()
print("Line 2:", line2.strip())

# Reset pointer again to show readlines() example
file.seek(0)

# 3️⃣ Read all lines as a list using readlines()
print("----- Using readlines() -----")
lines = file.readlines()
print(lines) # Each line is an element in the list

# Close the file after reading
file.close()

# ================================
# Example Output (if demo.txt contains):
# Hello World
# Welcome to Mohit Decodes
# File Handling in Python
# ================================
# Output:
# ----- Using read() -----
# Hello World
# Welcome to Mohit Decodes
# File Handling in Python
#
# ----- Using readline() -----
# Line 1: Hello World
# Line 2: Welcome to Mohit Decodes
#
# ----- Using readlines() -----
# ['Hello World\n', 'Welcome to Mohit Decodes\n', 'File Handling in Python\n']
# ================================