Path: utzoo!utgpu!cs.utexas.edu!swrinde!elroy.jpl.nasa.gov!sdd.hp.com!spool.mu.edu!uunet!mcsun!hp4nl!charon!piring.cwi.nl!guido From: guido@cwi.nl (Guido van Rossum) Newsgroups: alt.sources.d Subject: Re: shell pipeline to reverse the order of lines. Message-ID: Date: 20 Feb 91 17:30:53 GMT References: <9102151917.AA04419@wendy-fate.UU.NET> <3*-&S|^@rpi.edu> <1991Feb17.021452.21206@alphalpha.com> <1991Feb17.232832.18326@convex.com> Sender: news@cwi.nl Lines: 47 tchrist@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 [disclaimer: all code above untested]