How to read specific lines from a file in Python
A common way to read files in Python is to read the file completely and then process specific lines. Reading files in Python is fast, for example, it takes about 0.67 seconds to write a 100MiB file. However, if the file size exceeds 100MB, it will cause memory issues when reading it into memory.
Python has 3 built-in methods to read specific lines from a file, as described in the following sections.
fileobject.readlines()
Read specific lines of a small file
fileobject.readlines()
Reads all file contents into memory. It can use list slicing to read specific lines.
If we only need to read line 10,
with open("file.txt") as f:
data = f.readlines()[10]
print(data)
If we need to read 10 to 100 rows,
with open("file.txt") as f:
data = f.readlines()[10:100]
print(data)
Loop over file object for
to read specific lines in Python
For file objects, for line
it is also a fast solution for small files.
lines = [10, 100]
data = []
i = 0
with open("file.txt", "r+") as f:
for line in f:
if i in lines:
data.append(line.strip)
i = i + 1
print(data)
linecache
Module to read specific lines in Python
linecache
For reading many files, you can repeat or extract many lines:
import linecache
data = linecache.getline("file.txt", 10).strip()
String method strip()
Returns a string with spaces removed from both ends.
linecache
The module allows you to get any line from a Python source file while using caching for internal optimizations, a common practice for reading multiple lines from a single file. The traceback module uses it to retrieve source code lines for inclusion in a formatted traceback.
enumerate
Function
to read specific lines from a large file in Python
Larger files may cause problems such as out of memory when reading the file. In this case, we can use enumerate()
:
with open("file.txt") as f:
for i, line in enumerate(f):
pass # process line i
Note that for row n, i = n-1
.
enumerate()
Functions are used to combine traversable data objects (such as lists, tuples, or strings) into indexed sequences, listing both the data and the data subscripts, typically for
using a loop in .
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Read the first line of a file in Python
Publish Date:2025/05/05 Views:192 Category:Python
-
In Python, we have built-in functions to handle different file operations. A text file contains a sequence of strings where each line \n is terminated by a newline character. In this tutorial, we will learn how to read the first line of a t
Calculating the arithmetic mean in Python
Publish Date:2025/05/05 Views:190 Category:Python
-
The term arithmetic mean is the average of the numbers. The mathematical formula to determine the arithmetic mean is to divide the sum of the numbers by the count. It is determined in Python in the following way. Use mathematical formulas.
Cosine Similarity in Python
Publish Date:2025/05/05 Views:81 Category:Python
-
Cosine similarity measures the similarity between two lists of vectors by calculating the cosine angle between them. If you consider the cosine function, it has a value of 1 at 0 degrees and -1 at 180 degrees. This means that for two overla
Exponential and Logarithmic Curve Fitting in Python
Publish Date:2025/05/05 Views:79 Category:Python
-
Curve fitting is a very effective tool that is widely used in analysis. Curve fitting method studies the relationship between independent variables (also called predictor variables) and dependent variable (called response variable). This me
Calculating Slope in Python
Publish Date:2025/05/05 Views:60 Category:Python
-
In mathematics, the slope of a given line is the value at which its steepness is calculated. It also helps to characterize the direction of a given line. The extent of a line can also be calculated using Python programming language. This ar
How to Randomly Select Elements from a List in Python
Publish Date:2025/05/05 Views:68 Category:Python
-
This tutorial showed you how to randomly select an element from a list in Python. There are multiple simple ways to achieve this goal, all of which involve importing Python modules. This tutorial will cover solutions that require the random
How to Replace an Element in a Python List
Publish Date:2025/05/05 Views:109 Category:Python
-
We can replace elements in Python lists in many ways. We can use Python list element indexing, for loops, map functions, and list comprehensions. This article will discuss the above methods to find and replace elements in Python lists. Sear
Convert Tensor to NumPy array in Python
Publish Date:2025/05/03 Views:86 Category:Python
-
This tutorial will show you how to convert a Tensor to a NumPy array in Python. Use the function in Python Tensor.numpy() to convert a tensor to a NumPy array Eager Execution of TensorFlow library can be used to convert tensor to NumPy arra
Saving NumPy arrays as images in Python
Publish Date:2025/05/03 Views:194 Category:Python
-
In Python, numpy module is used to manipulate arrays. There are many modules available in Python that allow us to read and store images. An image can be thought of as an array of different pixels stored at specific locations with correspond