FirstHack 2026 — a 36-hour online hackathon built for first-year students.•₹1,00,000 prize pool•22 Oct – 4 Nov•Open to every branch and every stream•Certificate for every team that submits•3 rounds•FirstHack 2026 — a 36-hour online hackathon built for first-year students.•₹1,00,000 prize pool•22 Oct – 4 Nov•Open to every branch and every stream•Certificate for every team that submits•3 rounds•
Reading and writing files safely, and handling errors without hiding bugs.
12 min read·Lesson 6 of 6·Pro
Reading a file
Python 3
with open("marks.txt", "r") as f:
for line in f:
print(line.rstrip())
Three things are happening. open returns a file object. for line in f reads it one line at a time, so a 2 GB file uses almost no memory. line.rstrip() removes the trailing newline that readline leaves on.
The with is the important part. When the block ends - normally, or because an exception was raised - the file is closed automatically. Compare:
Python 3
f = open("marks.txt", "r")
data = f.read()
f.close() # never runs if f.read() raises
The rest of this lesson is Pro
The free lessons of Python for Engineering Students finish what
they start — read those first if you have not. This one goes further, and it
is part of the paid half.
A pass opens the paid lessons of every course, the mock test papers
and the company-wise series. It ends on its own date; nothing renews by itself.