Eleganz way to get rid of \n

josh logan dear.jay.logan at gmail.com
Mon Sep 1 09:37:14 EDT 2008


On Sep 1, 9:25 am, Hans Müller <HeinT... at web.de> wrote:
> Hello,
>
> I'm quite often using this construct:
>
> for l in open("file", "r"):
>         do something
>
> here, l contains the \n or \r\n on windows at the end.
> I get rid of it this way:
>
> for l in open("file", "r"):
>         while l[-1] in "\r\n":
>                 l = l[:-1]
>
> I find this a little bit clumsy, but it works fine.
>
> Has someone a better solution ?
>
> Thanks
>
> Hans

Can you do this:

f = open(fname)
for x in f:
    line = x.rstrip('\r\n')



More information about the Python-list mailing list