Monday 19 December 2011

Python usage

Python is case sensitive

#!/usr/bin/python

#Some string operation
int str.find(str,beg=0,end=len(str))  = -1 X

var = "H e l l o"  # for illustration purpose, it is Hello 
          0 1 2 3 4
var[2:4]==ll

var="""String start

                               StringEnf"""   # triple quote for block string

#Function to get seconds from  HH:MM:SS format
def getsec(strtime):
      a=s.split(':')
      return int(a[0])*3600 + int(a[1])*60 + int(a[2])

#Command line
    import sys
   argc=len(sys.argv)
# First argument
    sys.argv[1]

#Measure time difference  
from datetime import datetime
startTime=datetime.now()
...
endTime=datatime.now()
print "Time elapsed', endTime-startTime,endTime
#output
Time elapsed 0:00:01.667000 2011-12-19 20:28:12.470825


#Path and folder
currentpath=os.getcwd()  #import os

if(os.path.isdir(currentpath) == False):
   print "It is not a folder:",currentpath
   sys.exit("Exit 1")

#Open and write file
outputfile=open("myoutput.txt","w")
print>>outputfile,"This is a test line\n"
outputfile.close()

#List all file in the folder
def listallfiles(path)
  listing=os.listdir(path)
 for infile in listing:
     extension=os.path.splitext(infile)[-1].lower()
     if(extension == ".txt"):
          fulltextfilepath=path+"/"+infile
          readfile( fulltextfilepath)

#Open and read file
def reafile(filename):
   print "To open file %s" % filename
    myfile=open(filename,"r")
    for line in myfile:
         if(line.find('TAG') != -1):
             print line
    myfile.close()