On 02/02/13 22:46, Shane Green wrote:
with open(path) as input: for line in input: do(line)
Using with to create reference to opened file returned by open() so it could temporarily be assigned to input for the sole purpose of iterating its contents never sat very well with me.
It's not the *sole* purpose. If all you want it to iterate over the file, you can do this: for line in open(path): ... and no context manager is created. The context manager is also responsible for closing the file immediately you exit the block, without waiting for the caller to manually close it, or the garbage collector to (eventually) close it. So it is not *solely* for iteration. File context managers can also be used for more than just iteration: with open(path) as input: text = input.read() with open(path, 'r+') as output: output.write('ZZ') and so forth.
* The context manager returned by open() exists only to create the context and return reference "input"; * the context and code block created by the "with" only exists for inner "for" loop's code block to execute in.
I don't understand that objection. As I see it, that's a bit like saying "the len function exists only to get the length of objects". What did you expect the context manager to exist for if not to do the things you say? What am I missing? -- Steven