[Tutor] File parsing
Neha P
mywrkid at yahoo.com
Thu Jun 16 19:03:55 CEST 2011
Hi all,
I know below query may sound silly, but can somebody suggest any better way of doing this:
It would be helpful.
I need to read a file line by line and print each line starting from the last word first:
C:\Python26>type file_reversing_program.txt
import sys
import string
f_obj=open(sys.argv[1],"r")
for eachline in f_obj:
eachline=eachline[ :-1]# to eliminate the trailing "\n"
list_words=eachline.split(" ")
list_words[0]=list_words[0]+"\n"# to add "\n" so that after line 1 is printed, line 2 should start on a new line
list_words.reverse()
for every_word in list_words:
print every_word,# 'comma' helps in printing words on same line,hence for last word we append "\n"
f_obj.close()
C:\Python26>type input_file.txt
"Hi ther, how are you?"
I are doing fine, thank you.
C:\Python26>file_reversing_program.py input_file.txt
you?" are how ther,"Hi
you. thank fine, doing are I
Is there a better way of doing the above program, mainly the text highlighted in yellow,
Also if that is settled can there be a logic for getting the ouput more properly formatted (for text in blue) ,
say giving an output like :
"you? are how ther, Hi"
you. thank fine, doing are I
Thanks,
Neha
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110616/ec28787f/attachment.html>
More information about the Tutor
mailing list