Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good form to iterate through a file using only a for loop? [duplicate]

I've come across some code that iterates through lines in a file like so:

for line in open(filename, 'r'):
    do_all_the_things()

Is that a more Pythonic version of something like:

with open(filename, 'r') as f:
    for line in f:
        do_all_the_things()

It uses less indentation levels, so it looks nicer, but is it the same? From what I know, with basically adds a finally: f.close() or something to that effect to ensure after leaving the block the object is cleaned up. When the first for loop ends (or is cut short with a break perhaps) and the variable goes out-of-scope does the same thing happen? Can I take my cue from the first bit of code and save myself some keystrokes, or rather, should I fix it?

like image 925
Nick T Avatar asked Jan 24 '26 03:01

Nick T


1 Answers

You're not creating any reference to the file object other than within the iterator used by the for loop.

That means as soon as the for loop ends, that iterator, then the file object, will have their reference counts go to zero and they will be deleted.

When a file object is deleted, it is closed.

So you're not leaving open files by using the bare for loop.

That said, in a larger program, it's good to be explicit -- and the with statement says clearly that the file is used only within that context.

Personally, if I'm opening a file for writing / appending, then I'll use with even if I'm only using it in one place. If I'm just opening it for reading and not creating an explicit reference, I just use the object directly.

like image 141
agf Avatar answered Jan 26 '26 16:01

agf