Sharing: File Reader Generator with & w/o Policy

Mark H Harris harrismh777 at gmail.com
Sat Mar 15 20:36:21 EDT 2014


On 3/15/14 4:56 PM, MRAB wrote:

> I don't like how it always swallows the exception, so you can't tell
> whether the file doesn't exist or exists but is empty, and no way to
> specify the file's encoding.

Yes, the error handling needs more robustness/ and instead of printing
the errcode, my actual model on system will log it.
>
> Why do you have the 'finally' clause with 'None' in it? Instead of None
> you should have 'pass', or, better yet, omit the clause entirely.

Its a stub-in really, and that's all at this point.  The 'finally' 
happens regardless of whether the exception occurs, and I don't need
anything there yet, just don't want to forget it.

I've been playing around with wrapping generators within generators for 
readability and simplicity. Like this, where I'm going to wrap the 
fnName(filename) generator within a getnumline(filename) wrapper:

 >>> from my_utils import *

 >>> def getnumline(filename):
	      for record in fnName(filename):
		      yield(record)

 >>> line = getnumline("my_foxy")
 >>>
 >>> next(line)
(0, 26, 'The quick brown fox jumped')
 >>>
 >>> next(line)
(1, 25, "over the lazy dog's tail.")
 >>>

Or this, where I put it all in memory as a dict:

 >>> d1={}
 >>> for line in getnumline("my_foxy"):
	d1[line[0]]=(line[1], line[2])

 >>> for key in d1:
	print (d1[key])

(26, 'The quick brown fox jumped')
(25, "over the lazy dog's tail.")
(0, '')
(23, 'Now is the time for all')
(25, 'good women to come to the')
(24, 'aid of computer science!')
 >>>

marcus




More information about the Python-list mailing list