Difference between revisions of "Readfile.py"

From PeformIQ Upgrade
Jump to navigation Jump to search
 
Line 119: Line 119:


[[Category:Python]]
[[Category:Python]]
[[Category:Examples]]

Latest revision as of 17:09, 19 July 2009

Overview

Skeleton Python script which demonstrates reading a file - implemented using getopt() in a main() function and other niceties...

Script

#! /usr/bin/env python
#
#  Purpose: read a file
#
#  Copyright (C) Peter Harding, 2003
#                All rights reserved
#
#  $Id:$
#
#---------------------------------------------------------------------

import os
import sys
import getopt

#---------------------------------------------------------------------

__version__ = "1.0.0"

debugFlg    = 0
verboseFlg  = 0
filename    = "file.txt"

#---------------------------------------------------------------------

def rebuild(filename):
   try:
      f = open(filename, 'r')
   except IOError, msg:
      sys.stderr.write(filename + ': cannot open: ' + `msg` + '\n')
      sys.exit(1)

   lineno = 0

   while 1:
      line = f.readline()

      if not line: break

      lineno += 1

   f.close()

   print lineno

#---------------------------------------------------------------------

def main():
   global debugFlg
   global verboseFlg

   try:
      opts, args = getopt.getopt(sys.argv[1:], "dvV?")
   except getopt.error, msg:
      print __doc__
      return 1

   for o, a in opts:
      if o == '-d':
         debugFlg = 1
      elif o == '-v':
         verboseFlg = 1
      elif o == '-V':
         print "Version: %s" % __version__
         return 1
      elif o == '-?':
         print __doc__
         return 1

   if (debugFlg):
      print ">> Flg    %s" % debugFlg

   if args:
      for arg in args:
         print arg
   else:
      pass

   wrk = os.getcwd()

   base = os.path.basename(wrk)

   print wrk, base

   return 1

   rebuild()

#---------------------------------------------------------------------

if __name__ == '__main__' or __name__ == sys.argv[0]:
   sys.exit(main())

#---------------------------------------------------------------------

"""
Revision History:

     Date     Who   Description
   --------   ---   --------------------------------------------------
   20030920   plh   Initial implementation
   20031002   plh   Cleaned up args in main().  Added '-h', '-?', '-V'

Problems to fix:

To Do:

Issues:

"""