I have a code where I am reading all the lines from the file using readlines function and I am further parsing each line in a list. But when I printed the list I saw that the loop is ignoring the last line in the file. When I inserted a blank line in the file then all the contents are read. can you pls tell me why it is doing that
def readFile1(file1):
f = file1.readlines()
cList1 = []
for line in f:
if re.findall('\n',line):
v = re.sub('\n','',line)
cList1.append(v)
print cList1
This is printing all the contents except the last line of the file.
If the last line doesn’t end with a newline, your code won’t add it to
cList1. Instead, it would add a second copy of the penultimate line (which is still stored inv).A cleaner way to write that loop is:
Or, indeed:
In fact, I would avoid the
readlines()call entirely: