Read Specific Lines from a File in Python

In Python, you can read specific lines from a file using various approaches such as looping through the file, using list indexing, the readlines() method, or a combination of enumerate() and conditional statements. Below, we explore different ways to achieve this with examples.


Examples

1. Reading a Specific Line Using readlines()

The readlines() method reads all lines from a file and returns them as a list. You can use list indexing to access a specific line.

main.py

</>
Copy
# Open the file in read mode
with open("example.txt", "r") as file:
    lines = file.readlines()  # Read all lines into a list

# Read the third line (index 2 since indexing starts from 0)
specific_line = lines[2]  

# Print the result
print("Third line:", specific_line.strip())

Explanation

Here, we open the file example.txt in read mode and use readlines() to store all lines as a list in the lines variable. Since lists in Python use zero-based indexing, the third line is accessed using lines[2]. The strip() function removes trailing newline characters.

Output:

2. Reading Multiple Specific Lines Using enumerate()

We can use enumerate() to iterate through the file and extract specific lines based on their index.

main.py

</>
Copy
# Define the specific line numbers we want to read (0-based index)
line_numbers = [1, 2]

# Open the file in read mode
with open("example.txt", "r") as file:
    for i, line in enumerate(file):
        if i in line_numbers:
            print(f"Line {i+1}: {line.strip()}")

Explanation

Here, line_numbers is a list containing the indices of the lines we want to read. We use enumerate() to iterate through the file, which provides both the index (i) and the content (line). When i matches an index in line_numbers, we print the line.

Output:

3. Reading a Range of Lines Using islice() from itertools

The islice() function from the itertools module allows efficient reading of a specific range of lines.

main.py

</>
Copy
from itertools import islice

# Open the file in read mode
with open("example.txt", "r") as file:
    specific_lines = list(islice(file, 2, 5))  # Read lines 3 to 5 (zero-based indexing)

# Print the result
for i, line in enumerate(specific_lines, start=3):
    print(f"Line {i}: {line.strip()}")

Explanation

Here, we use islice(file, 2, 5) to extract lines from index 2 (third line) to index 5 (sixth line, exclusive). The enumerate() function ensures correct numbering.

Output:

Since we have only three lines in the example.txt, only the third line is printed to the output.

4. Using List Comprehension to Read Specific Lines

List comprehension provides a concise way to extract specific lines.

main.py

</>
Copy
# Define the line numbers to extract
line_numbers = {0, 2}

# Open the file and extract specific lines using list comprehension
with open("example.txt", "r") as file:
    selected_lines = [line.strip() for i, line in enumerate(file) if i in line_numbers]

# Print the result
for i, line in zip(sorted(line_numbers), selected_lines):
    print(f"Line {i+1}: {line}")

Explanation

We define line_numbers as a set of indices to extract. The list comprehension iterates over the file, keeping only the required lines. The zip() function ensures correct line numbering.

Output:

Conclusion

Python provides several ways to read specific lines from a file:

  1. readlines(): Stores all lines as a list, allowing direct indexing.
  2. enumerate(): Iterates through the file and extracts specific lines.
  3. islice() from itertools: Reads a range of lines efficiently.
  4. List Comprehension: A concise way to extract multiple specific lines.