Eleganz way to get rid of \n

H

Hans Müller

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
 
J

josh logan

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')
 
J

josh logan

The most general would be to use rstrip() without
arguments:



'some string'

but be careful, because it will also cut whitespaces:



'some string'

so maybe you could do this:



'some string\t '

HTH.

You can send both '\n' and '\r' in one rstrip call. No need for 2
separate calls.
 
B

Bruno Desthuilliers

Hans Müller a écrit :
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,
indeed.

but it works fine.

Has someone a better solution ?

help(str.rstrip)
 
F

Fredrik Lundh

Hans said:
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.

nope -- if you open a file in text mode (without the "b"), the I/O layer
will translate "\r\n" to "\n" on Windows.

if you want even more robust behaviour, use the "U" flag (for universal
newlines); that'll handle old-style Mac files too.

(as others have pointed out, a plain rstrip() is usually the best choice
anyway. giving meaning to trailing whitespace in text files is usually
a really lousy idea).

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,280
Latest member
BGBBrock56

Latest Threads

Top