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 open and enumerate functions.

For instance, if we have the following text file:

foo.txt:

foo
bar
baz

Then we can read the 3rd line of the file by writing:

with open("foo.txt") as fp:
    for i, line in enumerate(fp):
        if i == 2:
            print(line)

We call open with the path to the text file.

Then we loop through each line with the index i and line returned by enumerate.

We check if i is 2 to check if it’s reading the 3rd line.

If that’s True, then we call print to print the line.

So we see ‘baz’ printed.

Conclusion

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

Leave a Reply

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