shell pipeline to reverse the order of lines.

Guido van Rossum guido at cwi.nl
Thu Feb 21 04:30:53 AEST 1991


tchrist at convex.COM (Tom Christiansen) writes:

>I think seeing versions in shell, perl, icon, lisp, and now C
>is good and healthy.

And here's one in Python.  Judge for yourself.  It prints the result on stdout.

def reverse(filename):
	fp = open(filename, 'r')
	lines = []
	while 1:
		line = fp.readline()
		if not line: break
		lines.insert(0, line) # Insert in front of list
	for line in lines:
		print line,

If you want to reverse the file in place, replace the last two lines by:

	fp = open(filename, 'w')
	for line in lines:
		fp.write(line)

To make it into a script that reverses several files in place, add (to
the end, outside the function definition):

import sys
for filename in sys.argv[1:]:
	reverse(filename)

A more general function in Python to reverse the elements of any list
(actually it returns a reversed copy):

def revlist(list):
	result = []
	for item in list:
		result.insert(0, item)
	return result

This version uses 4*len(list) bytes of memory (if pointer size is 4
bytes) and can show quadratic behaviour (this depends on the
implementation of lists and in practice this is indeed the case).  It
could be improved by reversing smaller chunks and then concatenating
these but it would get hairier than I care about.  Reversing in place
would also be a possibility.

--Guido van Rossum <guido at cwi.nl> [disclaimer: all code above untested]



More information about the Alt.sources.d mailing list