How to read first N lines of a file?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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.
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.
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.
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.
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:
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
Nlines. - 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
islicealready 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.isliceis a clean iterator-based option.headis often the best answer for shell-only inspection.- Avoid loading the full file unless you actually need the full contents.
Related reading
- How to read the RGB value of a given pixel in Python?
- How to redirect 'print' output to a file?
- How to redirect TensorFlow logging to a file?
- How to register python microservices with my eureka server spring boot
- how to reimport module to python then code be changed after import
- How to reinstall python2 from Homebrew?
- How to reliably open a file in the same directory as the currently running script
- How to remove all characters after a specific character in python?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.