Python Practice › File Handling Programs › Program 6
Get a specific line
Write a Python program to get a specific line (by number) from a file.
Output
third None
Approach
- Loop with
enumerate(f, start=1)and stop at the wanted line.
Solution
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.
Learn the concept
New to this topic? Read the lesson, then come back.