I am reading the lines of a file and storing them in an array. The contents of the file are as follows -
hi
hello
bi
bello
I am writing a program to reverse the order of these words such that they are now written into a new file as
bello
bi
hello
hi
currently, I am reading the file using
file1 = open('example.txt','r')
s = file1.readlines()
when i examine the array 's', it looks like this -
['hi\n', 'hello\n', 'bi\n', 'bello']
now I was using s[::-1]
to reverse the order, but that results in the output looking something like -
bellohi
hello
bi
presumably because 'bello' is not follow by \n in the array where it is stored.
I have tried to fix it by manipulating the last term like this
s[-1]=s[-1]+'\n'
on the surface, it works - but am I unknowingly printing out an extra line or something or adding trailing spaces? Is there a better way to do this? Also why does the last string in the array not have a '\n'