{"id":9556,"date":"2021-06-13T18:24:27","date_gmt":"2021-06-13T12:54:27","guid":{"rendered":"https:\/\/pynative.com\/?p=9556"},"modified":"2021-07-03T12:08:58","modified_gmt":"2021-07-03T06:38:58","slug":"python-read-specific-lines-from-a-file","status":"publish","type":"post","link":"https:\/\/pynative.com\/python-read-specific-lines-from-a-file\/","title":{"rendered":"Read Specific Lines From a File in Python"},"content":{"rendered":"\n
This article lets you know how to read a specific lines from a file by line number in Python.<\/p>\n\n\n\n
Let’s assume the file to read is significantly large (in GB), and you don’t want to read the whole file in memory at once but only want to jump and read lines #5 and #120. To read specific lines from a text file, Please follow these steps:<\/p>
To open a file<\/a> pass file path and access mode Create a list<\/a> with the number of each line in a text file to read. After reading line 4 and 7 we will store result it in a list variable.<\/p> <\/li> The enumerate()<\/a> function adds a counter to an iterable and returns it in enumerate object. Pass the file pointer returned by the Use the if condition in each iteration of a loop to check the line number. If it matches, then save that line into a list.<\/p> <\/li><\/ol><\/div>\n<\/div>\n<\/div>\n\n\n\n The following code shows how to read a text file by line number <\/strong>in Python. See the attached file used in the example and an image to show the file\u2019s content for reference.<\/p>\n\n\n\n In this example, we are reading line number 4 and 7<\/strong> and storing it in a list variable.<\/p>\n\n\n\nr<\/code> to the
open()<\/code> function. The access mode specifies the operation you wanted to perform on the file, such as reading or writing.
For example, fp= open(r'File_Path', 'r')<\/code> to read a file<\/a>.<\/p> <\/li>
For example, line_numbers = [4, 7]<\/code>. Here we are reading lines 4 and 7.<\/p> <\/li>
open()<\/code> function to the
enumerate()<\/code>.
We can use this enumerate object with a for loop<\/a> to access the line number.
Note<\/strong>: enumerate(file_pointer)<\/code> doesn’t load the entire file in memory, so this is an efficient solution.<\/p> <\/li>
Example: Read specific lines from file by line number<\/h3>\n\n\n\n