Get a specific line

EasyFile Handling Programs · 6 of 38

Write a Python program to get a specific line (by number) from a file.

Advertisement
Output
third None

Approach

  1. Loop with enumerate(f, start=1) and stop at the wanted line.

Solution

Python
with open("story.txt", "w") as f:    f.write("first\nsecond\nthird\nfourth\n") def get_line(path, number):    with open(path) as f:        for i, line in enumerate(f, start=1):            if i == number:                return line.rstrip("\n")    return None print(get_line("story.txt", 3), get_line("story.txt", 9))
Output
third None

Line by line

Lines 5-8

Reading line by line stops as soon as the line is found, even in a huge file.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs