Reverse a file
Take a text file and reverse it the following ways: (1) reverse characters in each line, and (2) reverse the order of lines too. Let’s see an example:
#!/usr/bin/env python print "Please, reverse me completely!"
"!yletelpmoc em esrever ,esaelP" tnirp nohtyp vne/nib/rsu/!#
#!/usr/bin/env python # reverse-file.py import sys if len(sys.argv) < 2: print "Error: one argument is required!" exit(-1) try: f1 = open(sys.argv, 'r') except IOError: print "Error: the file cannot be opened." exit(-1) # else lines =  for line in f1: line = line.replace('\n', '') reversedLine = line[::-1] lines.append(reversedLine) f1.close() reversedLines = lines[::-1] for line in reversedLines: print line
The script requires a parameter which is the input file that we want to reverse. So first we check for a parameter. Then we try to open it in read-only mode. If the file doesn’t exist, drop an error message. Normally the error messages should go to the standard error with
sys.stderr.write(...), but for a small script it’s also good.
OK, now let’s see the real stuff. For each line in the file do the following: read it, remove the newline character at the end, reverse it, and put the reversed line in a list. When all lines are read, there are two more things to do: reverse the list that contains the reversed lines and print the lines.
What is it good for? Well, that will turn out in the next post :) Stay tuned!
Update (20100928): One might say that this code is too long and “in Perl I could do it in two lines”. Okay, here is more concise solution then:
#!/usr/bin/env python import sys for line in open(sys.argv, 'r').readlines()[::-1]: print line[::-1].replace('\n', '')
Here the real code is two lines only. First, open the file that was passed as the first argument in read-only mode. Verifications are omitted this time. Then
readlines() reads all the lines of the file in a list. This list is reversed. After this we start enumerating this reversed list using the
line variable. If the file contains
N lines, then line receives the
Nth line, then the
(N-1)th line, …, finally the 1st line. With each line, do the following: reverse it, remove the newline (which is the first character after the reversal), and print it (Python’s print automatically adds a newline). That’s it.