Sharing: File Reader Generator with & w/o Policy

Mark H Harris harrismh777 at gmail.com
Sat Mar 15 20:45:57 EDT 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?

marcus



More information about the Python-list mailing list