Reputation: 11
I am currently writing a static function where an open file object is passed in as a parameter. It then reads the file, and if the line is empty, it returns False. If the line is not empty, it uses the line in question plus the next three to create a new object of Person class (the class being designed in my module). For some reason, my if statement is not catching newlines, no matter what method I have tried, and I keep getting errors because of it. What am I doing wrong?
@staticmethod
def read_person(fobj):
p_list = []
for line in fobj:
if line.isspace() or line == "\n":
return False
else:
p_list.append(line)
return Person(p_list[0],p_list[1],p_list[2],p_list[3])
Thanks for your help!
Upvotes: 1
Views: 228
Reputation: 22483
The magic you want is:
if line.strip() == "":
You can get caught up in all the little cases possible in blank line processing. Is it space-newline? space-space-newline? tab-newline? space-tab-newline? Etc.
So, don't check all those cases. Use strip()
to remove all left and right whitespace. If you have an empty string remaining, it's a blank line, and Bob's your uncle.
Upvotes: 1