Python
File Handling
Programming Tips
Code Snippets
Beginner Tutorial

How to read first N lines of a file?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Reading the first N lines of a file is simple, but the best approach depends on whether you need a preview for display, a list of lines for later processing, or a shell-style quick check. In Python, the main goal is to stop early instead of loading the whole file unnecessarily.

Basic Python Loop with readline

A straightforward approach is to open the file and call readline() up to N times.

python
1def print_first_n_lines(path, n):
2    with open(path, "r", encoding="utf-8") as f:
3        for _ in range(n):
4            line = f.readline()
5            if not line:
6                break
7            print(line.rstrip("
8"))

This works well for simple preview tasks and stops cleanly if the file has fewer than N lines.

Use itertools.islice for Cleaner Python

If you want a more Pythonic iterator-based solution, itertools.islice is often nicer.

python
1from itertools import islice
2
3with open("data.txt", "r", encoding="utf-8") as f:
4    for line in islice(f, 5):
5        print(line.rstrip("
6"))

This is especially readable because it says directly: take only the first few lines from the file iterator.

Return the Lines Instead of Printing Them

Sometimes you want to keep the lines for later use.

python
1from itertools import islice
2
3
4def read_first_n_lines(path, n):
5    with open(path, "r", encoding="utf-8") as f:
6        return [line.rstrip("
7") for line in islice(f, n)]

This is a good pattern when the result will be shown in a UI, parsed further, or used in tests.

Shell Tools Are Still Useful for Quick Inspection

If the task is purely operational and you are already in a shell, head is the obvious tool.

bash
head -n 5 data.txt

That is often faster and simpler than writing Python at all when you only want a manual preview.

Why Not Read the Whole File?

A beginner mistake is:

python
lines = open("data.txt").readlines()
first_five = lines[:5]

That works, but it reads the entire file into memory before slicing. For a large file, that is wasteful when you only need the beginning.

The better solutions stop after N lines, which is exactly what makes them scalable.

Preserve or Remove Newlines Intentionally

Some code examples strip trailing newline characters for display, but not every use case should do that. If the first N lines are being forwarded to another parser or written back out, preserving the original line endings may be the correct behavior. The right choice depends on whether you are previewing text or preserving file content faithfully.

This Pattern Works Well for Large Logs

Previewing the first lines is especially useful with large log files, exported datasets, or generated reports where opening the whole file would be wasteful. Because the file is streamed line by line, the memory cost stays small even when the file itself is very large. That makes early-line reading a practical inspection tool, not only a beginner exercise.

Common Pitfalls

  • Reading the entire file when only a small prefix is needed.
  • Forgetting that the file may contain fewer than N lines.
  • Dropping encoding handling in text-processing code where file content may not be ASCII.
  • Confusing preview use cases with parsing use cases that need to preserve newline characters exactly.
  • Writing more manual loop code than necessary when islice already fits the problem well.

Summary

  • In Python, the best solutions read only as many lines as needed.
  • readline() in a loop is simple and explicit.
  • itertools.islice is a clean iterator-based option.
  • head is often the best answer for shell-only inspection.
  • Avoid loading the full file unless you actually need the full contents.

Course illustration
Course illustration

All Rights Reserved.