Python Practice › File Handling Programs › Program 4
First three and last three lines
Write a Python program to get the first three and last three lines of a file.
Output
First: ['line 1', 'line 2', 'line 3'] Last: ['line 8', 'line 9', 'line 10']
Approach
- Read all lines into a list and slice it.
Solution
with open("story.txt", "w") as f: f.write("\n".join(f"line {i}" for i in range(1, 11)) + "\n") with open("story.txt") as f: lines = f.read().splitlines()print("First:", lines[:3])print("Last:", lines[-3:])Output
First: ['line 1', 'line 2', 'line 3'] Last: ['line 8', 'line 9', 'line 10']
Line by line
Line 5
splitlines() gives the lines without newline characters.
Learn the concept
New to this topic? Read the lesson, then come back.