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’.
1 |
file_path = 'example.txt'<br>file = open(file_path, '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.
1 |
lines = file.readlines() |
Remember to close the file once you are done reading its content.
1 |
file.close() |
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.
1 |
selected_lines = [lines[0], lines[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.
1 2 |
for line in selected_lines: print(line.strip()) |
The strip() function is used to remove any leading or trailing whitespaces (such as newline characters) from each line when printing.
Full Code
1 2 3 4 5 6 7 8 9 |
file_path = 'example.txt' file = open(file_path, 'r') lines = file.readlines() file.close() selected_lines = [lines[0], lines[2]] for line in selected_lines: print(line.strip()) |
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:
Output
Line 1 Line 3
Conclusion
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.