How To Print Certain Lines From A Text File In Python

Printing certain lines from a text file is a common operation when working with files in Python.

It can be useful for analyzing log files, extracting specific data, or simple file filtering. In this tutorial, we’ll walk through the steps necessary to print specific lines from a text file in Python using built-in functions and modules.

Step 1: Open the File

To open a file in Python, you can use the open() function. This function takes two parameters: the file path and the mode in which the file will be opened. We’ll use the read mode, which is represented by the character ‘r’.

Step 2: Read the File

To read the content of the file, we can use the readlines() function. The function returns a list containing each line of the file as a separate item.

Remember to close the file once you are done reading its content.

Step 3: Pick Certain Lines

Once we’ve read the file into a list, we can use Python list slicing to extract the specific lines we want. Note that in Python, list indices start at 0, so if you want the first and the third lines, you have to use indices 0 and 2.

Step 4: Print the Selected Lines

Now that we have a list of selected lines, we can print them out using a for loop.

The strip() function is used to remove any leading or trailing whitespaces (such as newline characters) from each line when printing.

Full Code

Assuming the content of example.txt is as follows:

Line 1
Line 2
Line 3
Line 4
Line 5

The output of the code above would be:


Line 1
Line 3


In this tutorial, we’ve demonstrated how to print specific lines from a text file in Python. This process involved opening the file, reading its content into a list, selecting the desired lines, and then printing them. Remember to always close your files after reading or writing to them to prevent unwanted file corruption or memory leaks.