In this tutorial, we are going to learn how to read a specific line from a text file in Python. Fetching specific lines from a text file is a common requirement in Python coding, especially while handling large amounts of data stored in files.
Step 1: Creating a Sample Text File
First, we need a sample text file to work with. Here’s an example:
This is line 1 This is line 2 This is line 3 This is line 4 This is line 5
Step 2: Implementing Python Code for Reading a Specific Line
Next, we are going to use Python’s built-in open() function to fetch a particular line from the text file. Here’s how:
1 2 3 4 |
def read_specific_line(file_name, line_number): with open(file_name, 'r') as file: lines=file.readlines() return lines[line_number - 1] |
In the above function, ‘file_name’ is the name of the file, and ‘line_number’ is the number of the line we want to read.
Step 3: Testing the Function
We can test the function by providing it with the filename and the line number we want to read. Let’s say we want to read the 3rd line:
1 |
print(read_specific_line('sample.txt', 3)) |
The above code should return the 3rd line from sample.txt:
This is line 3
The Full Code
Now that we’ve walked through each part, here is the full code:
1 2 3 4 5 6 |
def read_specific_line(file_name, line_number): with open(file_name, 'r') as file: lines=file.readlines() return lines[line_number - 1] print(read_specific_line('sample.txt', 3)) |
Conclusion
Reading a specific line from a text file is a fairly simple task in Python with the help of the open() function. This process can be customized based on how you want to manipulate and utilize the data in these lines. For more on Python’s file handling and I/O capabilities, check out the official Python documentation.