Friday, October 1, 2010

How to reverse a file using python?

To reverse a file (i.e the last line become the first line etc),
the simple way is to use reversed builtin function, but python version at
least 2.4.


check python version: python -v
check builtin function: dir(__builtins__)
code for reverse a file, reverse.py
--------------------------------------------------
#!/usr/bin/env python

import sys

for line in reversed(open("mytube.txt").readlines()):
      print line.rstrip()


To take input argument:
--------------------------------------------------
#!/usr/bin/env python

import sys

for line in reversed(open(sys.argv[1]).readlines()):
      print line.rstrip()

No comments:

Post a Comment