Reading Text Files
Python makes reading files easy with the open() function. Learn to read entire files, line by line, and handle encoding.
15 min•By Priygop Team•Updated 2026
Reading Files
Reading Files
# Basic file reading
# with open("data.txt", "r") as f:
# content = f.read() # entire file as string
# print(content)
# Read lines
# with open("data.txt") as f:
# lines = f.readlines() # list of lines
# for line in lines:
# print(line.strip())
# Memory-efficient line-by-line
# with open("large_file.txt") as f:
# for line in f: # iterator, doesn't load all
# print(line.strip())
# Demo with io.StringIO (simulates a file)
import io
fake_file = io.StringIO("""Name,Age,City
Alice,25,Mumbai
Bob,30,Delhi
Charlie,28,Bangalore""")
# Read all
content = fake_file.read()
print("Full content:")
print(content)
# Reset position and read lines
fake_file.seek(0)
print("\nLine by line:")
for line in fake_file:
print(f" {line.strip()}")
# Read specific number of characters
fake_file.seek(0)
first_20 = fake_file.read(20)
print(f"\nFirst 20 chars: '{first_20}'")Tip
Tip
Always use 'with open()' for file handling. It automatically closes the file even if an error occurs.
Diagram
Loading diagram…
Everything in Python is an object — use type() to check
Common Mistake
Warning
Opening a file without 'with' and forgetting to close it leaks resources. Always use the context manager pattern.
Practice Task
Note
(1) Read a text file line by line. (2) Count lines and words. (3) Read only the first 100 characters.