Reverse Data File

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Jun 2007
Posts: 1
Reputation: cameyo is an unknown quantity at this point 
Solved Threads: 0
cameyo cameyo is offline Offline
Newbie Poster

Reverse Data File

 
0
  #1
Jun 28th, 2007
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)

Example:
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

cameyo
Reply With Quote Quick reply to this message  
Join Date: May 2007
Posts: 15
Reputation: ffao is an unknown quantity at this point 
Solved Threads: 4
ffao ffao is offline Offline
Newbie Poster

Re: Reverse Data File

 
0
  #2
Jun 28th, 2007
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.

  1. inp = open("somefile", "r")
  2. out = open("anotherfile", "w")
  3.  
  4. out.write("\n".join(" ".join(reversed(i.rstrip().split())) for i in reversed(inp.readlines())))
  5.  
  6. inp.close()
  7. out.close()

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

  1. #we will produce each line one by one and store here
  2. result = []
  3.  
  4. for i in reversed(inp.readlines()): # get the lines in reverse fashion
  5. i = i.rstrip() # strip trailing newline
  6. # split the data into a list, then reverse the order and join back with one space separating data
  7. string = " ".join(reversed(i.split()))
  8. #the line is correct, add it to the list
  9. result.append(string)
  10.  
  11. #join all of the lines, inserting a newline in-between
  12. write_str = "\n".join(result)
  13.  
  14. #write
  15. out.write(write_str)
Last edited by ffao; Jun 28th, 2007 at 10:18 am. Reason: use rstrip()
Reply With Quote Quick reply to this message  
Join Date: Jan 2006
Posts: 237
Reputation: katharnakh is an unknown quantity at this point 
Solved Threads: 33
katharnakh's Avatar
katharnakh katharnakh is offline Offline
Posting Whiz in Training

Re: Reverse Data File

 
0
  #3
Jun 28th, 2007
Hi Cameyo,

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

kath.
Last edited by katharnakh; Jun 28th, 2007 at 10:40 am.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC