Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: how to check if a line is an empty line

Tags:

python

Trying to figure out how to write an if cycle to check if a line is empty.

The file has many strings, and one of these is a blank line to separate from the other statements (not a ""; is a carriage return followed by another carriage return I think)

new statement asdasdasd asdasdasdasd  new statement asdasdasdasd asdasdasdasd 

Since I am using the file input module, is there a way to check if a line is empty?

Using this code it seems to work, thanks everyone!

for line in x:      if line == '\n':         print "found an end of line"  x.close() 
like image 499
user1006198 Avatar asked Oct 25 '11 22:10

user1006198


People also ask

How check string is null or not in Python?

Use len to Check if a String in Empty in Python Let's see how we can use this function to check if a string is empty or not: # Using len() To Check if a String is Empty string = '' if len(string) == 0: print("Empty string!") else: print("Not empty string!") # Returns # Empty string!

How do I check if a string contains a newline in Python?

Check if a string contains newlines using the 'in' operator With the 'in' operator, we can check for a specified value in a string. However, this method returns True if the value exists. Otherwise, returns False.

How do you check for blank spaces in a string in Python?

Python String isspace() Method The isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters such as: ' ' – Space. '\t' – Horizontal tab.


2 Answers

If you want to ignore lines with only whitespace:

if line.strip():     ... do something 

The empty string is a False value.

Or if you really want only empty lines:

if line in ['\n', '\r\n']:     ... do  something 
like image 80
retracile Avatar answered Sep 26 '22 13:09

retracile


I use the following code to test the empty line with or without white spaces.

if len(line.strip()) == 0 :     # do something with empty line 
like image 26
bevardgisuser Avatar answered Sep 24 '22 13:09

bevardgisuser