1.11M Members

Python: Reverse lines in a text file.

 
0
 

Greetings,

I found the equivalent of this in Java but not Python. What i'm trying to figure out is how to reverse and print each of 5 lines in a text file backwards. I am able to take this:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
laborum


and get this:

murobal
tse di mina tillom tnuresed aiciffo iuq apluc ni tnus ,tnediorp non tatadipuc taceacco tnis ruetpecxE .rutairap allun taiguf ue erolod mullic esse
tilev etatpulov ni tiredneherper ni rolod eruri etua siuD .tauqesnoc odommoc ae xe piuqila tu isin sirobal ocmallu noitaticrexe durtson siuq ,mainev
minim da mine tU .auqila angam erolod te erobal tu tnudidicni ropmet domsuie od des ,tile gnicisipida rutetcesnoc ,tema tis rolod muspi meroL

by using this script:

f = open('lorumipsum.txt');

contents = f.read();
reversed = '';
for i in range(len(contents)):
reversed = contents + reversed;
print reversed;


this is not doing what i want it to do but i'm not sure how. what i want is this:


minim da mine tU .auqila angam erolod te erobal tu tnudidicni ropmet domsuie od des ,tile gnicisipida rutetcesnoc ,tema tis rolod muspi meroL
tilev etatpulov ni tiredneherper ni rolod eruri etua siuD .tauqesnoc odommoc ae xe piuqila tu isin sirobal ocmallu noitaticrexe durtson siuq ,mainev
tse di mina tillom tnuresed aiciffo iuq apluc ni tnus ,tnediorp non tatadipuc taceacco tnis ruetpecxE .rutairap allun taiguf ue erolod mullic esse
murobal


I want to reverse the first line, print, second line, print, third line,print, then fourth line, print.


I would really a example that explains the kind of reversing i want to do, or a link that gives an explanation.

Thank you.

 
0
 

Iterate file line by line and reverse each before printing.

 
0
 

As Tony stated, you can iterate over a file

#f = open('lorumipsum.txt');

# simulate the file 
f=["Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim\n",
 "veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit\n",
 "esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit\n",
 "anim id est\n",
 "laborum\n"]

for rec in f:
    print rec[::-1]  ## using slicing to reverse 

# but you can also do it with a loop
for rec in f:
    reversed_list = []
    for ctr in range(len(rec)-1, -1, -1):  ## go from last letter to the first
        ## string concatenation is slow and expensive
        ## append to a list and join()
        reversed_list.append(rec[ctr])
    print "".join(reversed_list)
 
0
 

If you google "reversing a string in python," you'd find that stackoverlfow has a nice answer (http://stackoverflow.com/questions/931092/reverse-a-string-in-python). So, for your code, we can do, and test:

str1 = '''Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
 veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit 
 esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
 laborum'''.replace(' ', '')

str2 = '''murobal
 tse di mina tillom tnuresed aiciffo iuq apluc ni tnus ,tnediorp non tatadipuc taceacco tnis ruetpecxE .rutairap allun taiguf ue erolod mullic esse
 tilev etatpulov ni tiredneherper ni rolod eruri etua siuD .tauqesnoc odommoc ae xe piuqila tu isin sirobal ocmallu noitaticrexe durtson siuq ,mainev
 minim da mine tU .auqila angam erolod te erobal tu tnudidicni ropmet domsuie od des ,tile gnicisipida rutetcesnoc ,tema tis rolod muspi meroL'''.replace(' ', '')

print str1[::-1] == str2 # Evaluates as True.

I removed the whitespace because there might've been a discrepancy between the output you got and the text pasted into the the daniweb editor. Though, I don't see why the code wouldn't work with whitespace as well.

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: