Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Read First n Lines of a File
In this article, we will show you how to read and print the first N lines of a text file using Python. This is useful when you need to preview large files or extract specific portions of text data.
Assume we have a text file named sample.txt with the following content ?
Good Morning Tutorials Point This is Tutorials Point sample File Consisting of Specific abbreviated source codes in Python Seaborn Scala Imagination Summary and Explanation Welcome user Learn with a joy
Method 1: Using readlines() with Slicing
The most straightforward approach is to read all lines using readlines() and slice the first N lines ?
# Create sample file content
sample_content = """Good Morning Tutorials Point
This is Tutorials Point sample File
Consisting of Specific
abbreviated
source codes in Python Seaborn Scala
Imagination
Summary and Explanation
Welcome user
Learn with a joy"""
# Write to file for demonstration
with open('sample.txt', 'w') as f:
f.write(sample_content)
# Read first N lines
N = 4
with open('sample.txt', 'r') as file:
lines_list = file.readlines()
print(f"The first {N} lines of the file:")
for line in lines_list[:N]:
print(line, end='')
The first 4 lines of the file: Good Morning Tutorials Point This is Tutorials Point sample File Consisting of Specific abbreviated
Method 2: Using a Loop with readline()
For memory efficiency with large files, read lines one by one using readline() ?
N = 3
with open('sample.txt', 'r') as file:
print(f"First {N} lines using readline():")
for i in range(N):
line = file.readline()
if line: # Check if line exists
print(line, end='')
else:
break # End of file reached
First 3 lines using readline(): Good Morning Tutorials Point This is Tutorials Point sample File Consisting of Specific
Method 3: Using itertools.islice()
The most memory-efficient approach for very large files uses itertools.islice() ?
import itertools
N = 5
with open('sample.txt', 'r') as file:
print(f"First {N} lines using islice():")
first_n_lines = itertools.islice(file, N)
for line in first_n_lines:
print(line, end='')
First 5 lines using islice(): Good Morning Tutorials Point This is Tutorials Point sample File Consisting of Specific abbreviated source codes in Python Seaborn Scala
Handling Edge Cases
Here's how to handle files with fewer than N lines ?
def read_first_n_lines(filename, n):
try:
with open(filename, 'r') as file:
lines = file.readlines()
actual_lines = min(n, len(lines))
print(f"Requested: {n} lines, Available: {len(lines)} lines")
print(f"Reading first {actual_lines} lines:")
for line in lines[:n]:
print(line, end='')
except FileNotFoundError:
print(f"File '{filename}' not found!")
# Test with more lines than available
read_first_n_lines('sample.txt', 15)
Requested: 15 lines, Available: 9 lines Reading first 9 lines: Good Morning Tutorials Point This is Tutorials Point sample File Consisting of Specific abbreviated source codes in Python Seaborn Scala Imagination Summary and Explanation Welcome user Learn with a joy
Comparison
| Method | Memory Usage | Best For |
|---|---|---|
readlines()[:N] |
High (loads entire file) | Small files |
readline() loop |
Low (line by line) | Medium files |
itertools.islice() |
Lowest (iterator) | Very large files |
Conclusion
Use readlines()[:N] for small files, readline() loop for medium files, and itertools.islice() for memory-efficient processing of large files. Always handle edge cases like missing files or fewer lines than requested.
