Sharing: File Reader Generator with & w/o Policy

Mark H Harris harrismh777 at
Sun Mar 16 01:45:57 CET 2014

On 3/15/14 4:56 PM, MRAB wrote:
> def fName(filename):
>     try:
>         with open(filename, 'r') as fh:
>             for linein in fh:
>                 yield linein.strip('\n')
>     except FileNotFoundError as err_code:
>         print(err_code)
> [snip]

The "with" confuses me because I am not sure specifically what happens 
in the context manager. I'm taking it for granted in this case that 
__exit__() closes the file?

I am finding many examples of file handling using the context manager, 
but none so far that wrap into a generator; more often and file object. 
Is there a preference for file object over generator?


More information about the Python-list mailing list