File Reading related query

Tim Chase python.list at tim.thechases.com
Wed Sep 17 06:45:44 EDT 2008


>> Is there any function for reading a file while ignoring *\n* occuring in 
>> the file?
> 
> can you be a bit more precise?  are we talking about text files or 
> binary files?  how do you want to treat any newlines that actually 
> appear in the file?

I believe the OP is referencing this behavior:

   for line in file('x.txt'):
     assert not (
       line.endswith('\r') or
       line.endswith('\n')), "Don't want this"
   else:
     yay()  # we never end up reaching this

which can be done with a simple generator/wrapper:

   def unnewline(iterator):
     for line in iterator:
       yield line.rstrip('\r\n')
   for line in unnewline(file('x.txt')):
     assert not (
       line.endswith('\r') or
       line.endswith('\n')), "Don't want this"
   else:
     yay()  #  we get here this time

Alternatively, the content can just be modified on the fly:

   for line in file('x.txt'):
     line = line.rstrip('\r\n')
     ...

yes, the interpretation would differ if it were a binary file, 
but the above interpretation is a pretty common case (i.e. I 
encounter it daily, in my processing of client data-feeds).

-tkc





More information about the Python-list mailing list