Python file.readline() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
file method

Definition

readline() reads one line from the current position, up to and including the newline character. The last line of a file may have no newline.

At the end of the file it returns an empty string or bytes object. A blank line is not empty: it comes back as "\n", so the two cases never mix up.

file.readline() is a method of the file objects that the built-in open() returns, so no import is needed. It works on text files (TextIOWrapper), binary files (BufferedReader, BufferedWriter, BufferedRandom), and raw files (FileIO, opened with buffering=0).

Syntax

Call it with no argument for a whole line, or with a size to cap the length.

python
line = f.readline()
line = f.readline(size)
CallWhat it does
f.readline()The next line, such as 'host=db1\n'.
f.readline(5)At most 5 characters (text) or bytes (binary) of the next line.
f.readline()At the end of the file: '' or b''.

In text mode the newline is "\n" by default, because \r\n and \r are translated while reading. Binary files keep whatever bytes are stored.

Method signatures
python
TextIOWrapper.readline(size=-1, /)    # -> str
BufferedReader.readline(size=-1, /)   # -> bytes
IOBase.readline(size=-1, /)           # FileIO and other streams

Parameters

ParameterDescription
sizeOptional. The maximum number of characters (text) or bytes (binary) to return. The rest of the line is left for the next call.

Return Value

Return ValueDescription
str / bytesOne line, ending with the newline unless it is the last line of a file without a final newline, or size cut it short.
'' / b''End of file.

Python Examples

Each example works inside a temporary folder that is deleted at the end, so nothing is left on your disk.

Example 1 — Read a CSV Header, Then the Rows

Take the header with readline(), then let a for loop continue from the second line.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "parts.csv")
    with open(path, "w", encoding="utf-8") as f:
        f.write("name,qty\nbolts,40\nnuts,25")

    with open(path, encoding="utf-8") as f:
        header = f.readline()
        print(repr(header))
        columns = header.rstrip("\n").split(",")
        for line in f:
            print(dict(zip(columns, line.rstrip("\n").split(","))))

How It Works

  1. Newline included. repr() shows the header still ends with \n; rstrip("\n") removes it before splitting.
  2. Loop picks up after it. The for loop starts at the second line because readline() already consumed the first.
  3. Rows as dicts. zip() pairs each column name with a value, and dict() builds one record per row.
  4. No final newline. The last row nuts,25 has no \n; rstrip handles both cases safely.

Example 2 — Tell a Blank Line from the End of the File

Read a config file with a blank line in the middle using a while loop.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "server.cfg")
    with open(path, "w", encoding="utf-8") as f:
        f.write("host=db1\n\nport=5432\n")

    with open(path, encoding="utf-8") as f:
        count = 0
        while True:
            line = f.readline()
            if line == "":
                break
            count += 1
            print(count, repr(line))

How It Works

  1. Explicit loop. The while True loop calls readline() until it returns exactly "".
  2. Blank line is "\n". Line 2 comes back as a one-character string, so the loop keeps going instead of stopping early.
  3. Real end. Only after port=5432 does readline() return the empty string that breaks the loop.

Example 3 — Cap a Log Line with readline(size)

Read just the severity word of a binary log line, then the rest, then the next line.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "alerts.log")
    with open(path, "wb") as f:
        f.write(b"ERROR: disk full\nOK\n")

    with open(path, "rb") as f:
        print(f.readline(5))
        print(f.readline())
        print(f.readline())
        print(f.readline())

How It Works

  1. Binary lines are bytes. Opening with "rb" makes each line a bytes object ending in b'\n'.
  2. Five bytes only. readline(5) stops after ERROR even though the line is longer.
  3. Rest of the line. The next call continues mid-line and returns the remainder with its newline.
  4. Empty bytes at the end. After OK, the fourth call returns b'', the binary end-of-file signal.

Frequently Asked Questions

So you can tell a blank line ("\n") from the end of the file (""). Strip it with line.rstrip("\n") when you do not need it.
It returns an empty string in text mode or b"" in binary mode. A blank line is never empty because it still contains the newline.
Use for line in f for ordinary loops. Use readline() when you need just one line, such as a header, or want to control the loop yourself.
It returns at most size characters (text mode) or bytes (binary mode) of the current line. The rest of the line is returned by the next call.
In text mode with the default newline=None, "\r\n" is translated to "\n". In binary mode, or with newline="", the "\r" is kept.

Next: file.readlines()

Read the remaining lines into a list, optionally stopping after about hint characters or bytes.

readlines() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful