home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / UNTABIFY.PY < prev    next >
Encoding:
Python Source  |  2000-09-28  |  1.2 KB  |  54 lines

  1. #! /usr/bin/env python
  2.  
  3. "Replace tabs with spaces in argument files.  Print names of changed files."
  4.  
  5. import os
  6. import sys
  7. import string
  8. import getopt
  9.  
  10. def main():
  11.     tabsize = 8
  12.     try:
  13.         opts, args = getopt.getopt(sys.argv[1:], "t:")
  14.         if not args:
  15.             raise getopt.error, "At least one file argument required"
  16.     except getopt.error, msg:
  17.         print msg
  18.         print "usage:", sys.argv[0], "[-t tabwidth] file ..."
  19.         return
  20.     for optname, optvalue in opts:
  21.         if optname == '-t':
  22.             tabsize = int(optvalue)
  23.  
  24.     for file in args:
  25.         process(file, tabsize)
  26.  
  27. def process(file, tabsize):
  28.     try:
  29.         f = open(file)
  30.         text = f.read()
  31.         f.close()
  32.     except IOError, msg:
  33.         print "%s: I/O error: %s" % (`file`, str(msg))
  34.         return
  35.     newtext = string.expandtabs(text, tabsize)
  36.     if newtext == text:
  37.         return
  38.     backup = file + "~"
  39.     try:
  40.         os.unlink(backup)
  41.     except os.error:
  42.         pass
  43.     try:
  44.         os.rename(file, backup)
  45.     except os.error:
  46.         pass
  47.     f = open(file, "w")
  48.     f.write(newtext)
  49.     f.close()
  50.     print file
  51.  
  52. if __name__ == '__main__':
  53.     main()
  54.