First three and last three lines

EasyFile Handling Programs · 4 of 38

Write a Python program to get the first three and last three lines of a file.

Advertisement
Output
First: ['line 1', 'line 2', 'line 3']
Last: ['line 8', 'line 9', 'line 10']

Approach

  1. Read all lines into a list and slice it.

Solution

Python
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.

More file handling programs

← All 38 File Handling Programs

Leave a Comment