
Output: linecache Module Read line from a file by line number Text file with open(r"E:\demos\files\read_demo.txt", 'r') as fp: In this example, we are reading line number 4 and 7 and storing it in a list variable.

See the attached file used in the example and an image to show the file’s content for reference.
#PYTHON FIND WORD IN FILE AND PRINT LINE HOW TO#
The following code shows how to read a text file by line number in Python. If it matches, then save that line into a list.Įxample: Read specific lines from file by line number Use the if condition in each iteration of a loop to check the line number. Note: enumerate(file_pointer) doesn’t load the entire file in memory, so this is an efficient solution. We can use this enumerate object with a for loop to access the line number. Pass the file pointer returned by the open() function to the enumerate(). The enumerate() function adds a counter to an iterable and returns it in enumerate object. Use for loop with enumerate() function to get a line and its number.Here we are reading lines 4 and 7.Īfter reading line 4 and 7 we will store result it in a list variable.

The access mode specifies the operation you wanted to perform on the file, such as reading or writing.įor example, fp= open(r'File_Path', 'r') to read a file.Ĭreate a list with the number of each line in a text file to read.įor example, line_numbers =. To open a file pass file path and access mode r to the open() function. To read specific lines from a text file, Please follow these steps: 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.
