2

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'

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 1
    Your input file as such does not end with a terminating new line after `bello`. It is sort of standard for the last line to be terminated with a new line character – Inian Sep 04 '19 at 06:09
  • Not just "sort of"; it is not a valid text file according to POSIX if the last newline is missing. – tripleee Sep 04 '19 at 06:10

2 Answers2

2

You can make the addition conditional:

if not s[-1].endswith('\n'):
    s[-1] += '\n'

Or you can normalize by removing any trailing newline and then put one back:

s[-1] = s[-1].rstrip('\n') + '\n'

I'd go with the former, but you see both approaches.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 1
    isn’t your approach the same as me doing - s[-1] = s[-1] + ‘\n’ ? only that at the moment i am not explicitly checking for \n at the moment –  Sep 04 '19 at 15:34
  • No, you are adding a newline even if the line already has one. – tripleee Sep 04 '19 at 15:52
0

See this answer for help to remove the \n from the list elements.

See this answer for help on how to reverse through a list.

This code will get you the list you want. Could be refactored better... but that can be a challenge for you.

s = ['hi\n', 'hello\n', 'bi\n', 'bello']
revList = list(reversed(s)) 

for i, e in enumerate(revList):
    revList[i] = e.strip("\n")
    if i < len(revList)-1:
        revList[i] = e + "\n"
print(revList)

When Python reads the file, it will read line breaks as they are strings. So the last word in the first file does not have a new line under it, so that's why it doesn't have "\n" in the list.

When you use [i-1] you are going backwards through the list, but you are keeping the line breaks in order. If you work through your code bit by bit, you will see why you get the output you are getting. Remember that computers take things literally.

Mr. J
  • 1,524
  • 2
  • 19
  • 42