Categories
Python Answers

How to jump to a particular line in a huge text file with Python?

Spread the love

Sometimes, we want to jump to a particular line in a huge text file with Python.

In this article, we’ll look at how to jump to a particular line in a huge text file with Python.

How to jump to a particular line in a huge text file with Python?

To jump to a particular line in a huge text file with Python, we’ve to read the file.

For instance, we write

# ...
line_offset = []
offset = 0
for line in file:
    line_offset.append(offset)
    offset += len(line)
file.seek(0)

# ...

file.seek(line_offset[n])

to loop through the file and append the offset to the line_offset list.

Then we add the line‘s length to the offset.

Next, we rewind back to the start of the file with file.seek called with 0.

And then we call file_seek again to jump to the offset with

file.seek(line_offset[n])

Conclusion

To jump to a particular line in a huge text file with Python, we’ve to read the file.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *