File Reading related query

Usman Ajmal uzmanajmal at gmail.com
Wed Sep 17 07:06:19 EDT 2008


Thanks Tim. That rstrip('\r\n') worked. :)

On Wed, Sep 17, 2008 at 10:45 AM, Tim Chase
<python.list at tim.thechases.com>wrote:

> 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
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080917/19c0bc33/attachment-0001.html>


More information about the Python-list mailing list