Categories
Python Answers

How to read specific lines from a file by line number with Python?

Spread the love

Sometimes, we want to read specific lines from a file by line number with Python.

In this article, we’ll look at how to read specific lines from a file by line number with Python.

How to read specific lines from a file by line number with Python?

To read specific lines from a file by line number with Python, we can use the enumerate function.

For instance, we write

with open("file.txt") as fp:
    for i, line in enumerate(fp):
        if i == 25:
            # ...
        elif i == 29:
            # ...
        elif i > 29:
            break

to open the file.txt file with open.

And then we loop through the lines with the index and line with enumerate.

line has the content of each line and i is the line‘s index.

Then we can use if statements to check the index of the line and do what we want.

Conclusion

To read specific lines from a file by line number with Python, we can use the enumerate function.

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 *