I have a delimited text file with some data.
I need to revert the data in this way:
1) the last line will be the first, and son on (invert all the lines)
2) each line must have a reverted data (last data item will be the first and so on)

file IN:
100 200 230
238 345 333
234 455 248

file OUT
248 455 234
333 345 238
230 200 100

can you help me ?

Thanks in advance


First, I have to tell you that the data will be separated by one space only, regardless of how many there were in the original file. This is a simple code which has no concerns whatsoever with memory/speed, as it keeps the whole file in memory.

inp = open("somefile", "r")
out = open("anotherfile", "w")

out.write("\n".join(" ".join(reversed(i.rstrip().split())) for i in reversed(inp.readlines())))


The fourth line is the one that does the job. Here it is, in a more friendly code block:

#we will produce each line one by one and store here
result = []

for i in reversed(inp.readlines()): # get the lines in reverse fashion
    i = i.rstrip() # strip trailing newline
    # split the data into a list, then reverse the order and join back with one space separating data
    string = " ".join(reversed(i.split())) 
    #the line is correct, add it to the list

#join all of the lines, inserting a newline in-between
write_str = "\n".join(result)


Hi Cameyo,

If you wish you can also go through this thread, which is recently discussed, which is for your further learning.


This article has been dead for over six months. Start a new discussion instead.