Opening a file: what is going on here with this instantiation?

I came across this short snippet of code to jump to a specific line (11 in this case) in a text file:

with open('mytextfile.txt') as f:
    for i in range(10):
        f, next(f)
    for line in f:

And it works great but I am totally clueless what the line

        f, next(f)

is doing. I didn’t even know it was possible to reference the file object without doing anything to it! What is going on here? I am much more used to doing something like this:

with open('anothertextfile.txt', 'r') as fileobj:
    for row in fileobj:

where fileobj is the entire file, is it not? So how is “f, next(f)” being used in the preceding example?

Cheers for any help

Not sure what the f, part is for because next(f) by itself on that line will work just fine. next can be used with any iterable, so f must be iterable. In this case, it basically just skips to the next line of the file each time it is called.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.