How to read specific lines from a File in Python?
Last Updated :
21 Mar, 2024
Text files are composed of plain text content. Text files are also known as flat files or plain files. Python provides easy support to read and access the content within the file. Text files are first opened and then the content is accessed from it in the order of lines. By default, the line numbers begin with the 0th index. There are various ways to read specific lines from a text file in python, this article is aimed at discussing them.
Method 1: fileobject.readlines()
A file object can be created in Python and then readlines() method can be invoked on this object to read lines into a stream. This method is preferred when a single line or a range of lines from a file needs to be accessed simultaneously. It can be easily used to print lines from any random starting index to some ending index. It initially reads the entire content of the file and keep a copy of it in memory. The lines at the specified indices are then accessed.
Example:
Python3
# open the sample file used
file = open('test.txt')
# read the content of the file opened
content = file.readlines()
# read 10th line from the file
print("tenth line")
print(content[9])
# print first 3 lines of file
print("first three lines")
print(content[0:3])
Output
tenth line
This is line 10.
first three lines
This is line 1.This is line 2.This is line 3.
Method 2: linecache package
The linecache package can be imported in Python and then be used to extract and access specific lines in Python. The package can be used to read multiple lines simultaneously. It makes use of cache storage to perform optimization internally. This package opens the file on its own and gets to the particular line. This package has getline() method which is used for the same.
Syntax:
getLine(txt-file, line_number)
Example:
Python3
# importing required package
import linecache
# extracting the 5th line
particular_line = linecache.getline('test.txt', 4)
# print the particular line
print(particular_line)
Output :
This is line 5.
Method 3: enumerate()
The enumerate() method is used to convert a string or a list object to a sequence of data indexed by numbers. It is then used in the listing of the data in combination with for loop. Lines at particular indexes can be accessed by specifying the index numbers required in an array.
Example:
Python3
# open a file
file = open("test.txt")
# lines to print
specified_lines = [0, 7, 11]
# loop over lines in a file
for pos, l_num in enumerate(file):
# check if the line number is specified in the lines to read array
if pos in specified_lines:
# print the required line number
print(l_num)
Output
This is line 1.
This is line 8.
This is line 12.
Similar Reads
How to Read from a File in Python Reading from a file in Python means accessing and retrieving the contents of a file, whether it be text, binary data or a specific data format like CSV or JSON. Python provides built-in functions and methods for reading a file in python efficiently.Example File: geeks.txtHello World Hello GeeksforGe
5 min read
How to remove blank lines from a .txt file in Python Many times we face the problem where we need to remove blank lines or empty spaces in lines between our text to make it look more structured, concise, and organized. This article is going to cover two different methods to remove those blank lines from a .txt file using Python code. This is going to
3 min read
How to Find the Longest Line from a Text File in Python Finding the longest line from a text file consists of comparing the lengths of each line to determine which one is the longest. This can be done efficiently using various methods in Python. In this article, we will explore three different approaches to Finding the Longest Line from a Text File in Py
3 min read
How to read Dictionary from File in Python? In Python, reading a dictionary from a file involves retrieving stored data and converting it back into a dictionary format. Depending on how the dictionary was savedâwhether as text, JSON, or binary-different methods can be used to read and reconstruct the dictionary for further use in your program
3 min read
How to read multiple text files from folder in Python? Reading multiple text files from a folder in Python means accessing all the .txt files stored within a specific directory and processing their contents one by one. For example, if a folder contains three text files, each with a single line of text, you might want to read each fileâs content and proc
3 min read