Check for new line character?

Y

Yazar Yolait

I want to skip lines in a file that are blank and that start with "&". So I
strip(None) them and then startswith("&") but the only problem is if the
line has nothing but white space and I strip(None) it then it contains
nothing but a new line character right? So how do I check if the line
contains a new line character? I can no longer use isspace().
 
J

John Roth

Yazar Yolait said:
I want to skip lines in a file that are blank and that start with "&". So I
strip(None) them and then startswith("&") but the only problem is if the
line has nothing but white space and I strip(None) it then it contains
nothing but a new line character right? So how do I check if the line
contains a new line character? I can no longer use isspace().

if line == '\n':
whatever...

If you're using <file>.readline() to
read the lines, then each line (except the eof signal) ***will*** end
with a newline, and it will not have a newline internally, so there's no
need for a complicated check. After you strip blanks, an all blank
line will contain exactly one character: the newline.

John Roth
 
E

Erik Max Francis

Yazar said:
I want to skip lines in a file that are blank and that start with "&".
So I
strip(None) them and then startswith("&") but the only problem is if
the
line has nothing but white space and I strip(None) it then it contains
nothing but a new line character right?

No, the newline character is whitespace as well so you'll be left with
the empty string:
'&'

So how do I check if the
line
contains a new line character? I can no longer use isspace().

Pretty basic:

while True:
line = inputFile.readline()
if not line:
break
line = line.strip()
if not line or line.startswith('&'):
continue
...

If the rest of your program is sensitive to (non-newline) whitespace,
then just strip the newline, change

line = line.strip()

to

if line[-1] == '\n':
line = line[:-1]
 
E

Erik Max Francis

John said:
If you're using <file>.readline() to
read the lines, then each line (except the eof signal) ***will*** end
with a newline, and it will not have a newline internally, so there's
no
need for a complicated check.

Not quite true. It's possible the file will be missing the final
newline, though Python will still treat it as a separate line:

max@oxygen:~/tmp% echo newline > test
max@oxygen:~/tmp% echo -n "no newline" >> test
max@oxygen:~/tmp% python
Python 2.3.2 (#1, Oct 3 2003, 15:44:45)
[GCC 3.2.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.''
 

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,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top