I´m reading a file in Python where each record is separated by an empty new line. If the file ends in two or more new lines, the last record is processed as expected, but if the file ends in a single new line it´s not processed. Here´s the code:
def fread():
record = False
for line in open('somefile.txt'):
if line.startswith('Record'):
record = True
d = SomeObject()
# do some processing with line
d.process(line)
if not line.strip() and record:
yield d
record = False
for record in fread():
print(record)
In this data sample, everything works as expected ('---' is an empty line):
Record 1
data a
data b
data c
\n
Record 2
data a
data b
data c
\n
\n
But in this, the last record isn´t returned:
Record 1
data a
data b
data c
\n
Record 2
data a
data b
data c
\n
How can I preserve the last new line from the file to get the last record?
PS.: I´m using the term "preserve" as I couldn´t find a better name.
Thanks.
Edit The original code was a stripped version, just to illustrate the problem, but it seems that I stripped too much. Now I posted all function´s code.
A little more explanation: The object SomeObject
is created for each record in the file and the records are separated by empty new lines. At the end of the record it yields back the object so I can use it (save to a db, compare to another objects, etc).
The main problem when the file ends in a single new line, the last record isn´t yielded. It seems that Python does not read the last line when it´s blank.