Home > python > Reverse a file

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!"

    f1 = open(sys.argv[1], 'r')
except IOError:
    print "Error: the file cannot be opened."

# else
lines = []
for line in f1:
    line = line.replace('\n', '')
    reversedLine = line[::-1]

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[1], '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.

Categories: python Tags: , ,
  1. yves
    September 28, 2010 at 15:23

    Actually your code contains 3 lines…
    Here is a 1-line solution:

    print "".join([l[::-1] for l in open(__import__("sys").argv[1], 'rt').readlines()[::-1]])


    • September 28, 2010 at 15:32

      Nice work. Reminds me of the good old times with Perl…

  1. September 28, 2010 at 11:06

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: