FirstHack Learn
Log in Sign up free
Lessons in this course 0/6 All courses Python for Engineering Students

First year

Progress0 / 6 lessons
  1. 1. Why Python reads the way it does
  2. 2. Variables, types and f-strings
  3. 3. Lists, tuples, dicts and sets
  4. 4. Loops, comprehensions and enumerate
  5. 5. Functions, default arguments and *args
  6. 6. Files, exceptions and context managers

Courses › Python for Engineering Students

Files, exceptions and context managers

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.

Get a pass — from ₹29 for 7 days

Already bought one? Log in.