2

So I'm trying to reverse all lines, but instead I get totaly strange reverse, it puts 4th line on the 1st line with the 5 line...

How file looks before reversing:

1 line
2 line
3 line
4 line
5 line

After reversing:

5 line4 line
3 line
2 line
1 line

Here is the code:

    file = open(filename, "r")
    list = file.readlines()
    file.close()

    list.reverse()

    file = open(filename, "w")
    for value in list:
        file.write(value)
    file.close()
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
Xerath
  • 1,069
  • 5
  • 17
  • 26
  • related: [Read a file in reverse order using python](http://stackoverflow.com/q/2301789/4279). See also [`reversed_lines()` function](http://stackoverflow.com/a/260433/4279) – jfs Apr 13 '14 at 01:26

2 Answers2

3

It seems that you didn't have the end line sign in the last line (the '\n'). It could be fixed easily by adding '\n' when needed:

file = open(filename, "w")
    for value in list:
         file.write(value.rstrip() + "\n")
    file.close()
tmrlvi
  • 2,235
  • 17
  • 35
  • use `with`-statement to close the file even if an exception happens: `with open(filename, 'w') as file: file.writelines(map(str.rstrip, lines))` – jfs Apr 13 '14 at 00:43
3

Every line of the file has a newline character \n at the end of it, except for the very last line.

The simplest way would be to do this:

file.open(filename,'r')
lines = file.read().split("\n")
file.close()
file = open(filename, "w")
file.write("\n".join(lines[::-1]))
file.close()

You could also try using str.strip() or str.rstrip() to remove all whitespace from the ends of a string or just the right end. This, however, would also remove spaces, tabs, etc.

dpinna
  • 3
  • 2
SimonT
  • 2,219
  • 1
  • 18
  • 32