Rudy Van Drie
Rudy Van Drie

Reputation: 91

Need to reverse File but last line has no Carriage Return, so first item of Reversed List has 2 lines in it

Here is the file

303620.43,6187793.62
303663.61,6187757.08
303652.22,6187702.51
303580.10,6187685.43
303551.63,6187737.15
303574.88,6187775.11
303610.94,6187773.69

When it is reversed I get

303610.94,6187773.69303574.88,6187775.11
303551.63,6187737.15
303580.10,6187685.43
303652.22,6187702.51
303663.61,6187757.08
303620.43,6187793.62

How do I ensure that the Last line when reversed has a '\n' ?

Upvotes: 0

Views: 223

Answers (3)

Jeannot
Jeannot

Reputation: 1175

+1 for larsmans response.An other solution is to use the splitlines method of string objects:

myFile = open(filePath, 'r')
lines = myFile.read().splitlines() #by default splitlines removes trailing '\n'
myFile.close()
lines.reverse()
for line in lines:
    print line

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363767

Use rstrip to remove the newline (and other trailing whitespace) off all lines, then rely on print to put it back in.

a = [ln.rstrip() for ln in open('datafile.txt')]
a.reverse()
for ln in a:
    print(ln)

Upvotes: 5

NPE
NPE

Reputation: 500733

In your code, after you've read a line, check that it ends in '\n'. If it doesn't, append a '\n' and carry on as you're doing already.

The endswith method will probably come in handy.

Upvotes: 1

Related Questions