<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-6767613935004460333</id><updated>2026-10-17T22:46:43.281-07:00</updated><category term="Python File Example"/><category term="Mail"/><category term="CSV Examples"/><category term="Strings"/><category term="Database"/><category term="MySQL"/><category term="Command Execution Using Python"/><category term="File Example"/><category term="List"/><category term="Python Date Example"/><category term="Python Example"/><category term="Python XML Parser"/><category term="Searching Example"/><category term="Control Structure"/><category term="Features of Python Programming Language"/><category term="IF Statement"/><category term="Multithreading"/><category term="Python Introduction"/><category term="Python Network Example"/><category term="Simple Calculation Program"/><category term="Zip File Example"/><title type='text'>Python Programs and Examples</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='next' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default?start-index=26&amp;max-results=25&amp;redirect=false'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>66</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-3975935212202557837</id><published>2012-10-26T10:38:00.000-07:00</published><updated>2012-10-26T10:38:00.412-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python File Example"/><title type='text'>Find text/pattern under parent folder from matched file names</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
The small piece of code take the folder
name and the pattern of the possible file names which might have the
text then it takes again the pattern/actual text which one is being
searched.&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
It prints the file name and line
searching out the folder.  
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
import os
import re
#import sys
#shutil


def matchline(line,match):
   #cmatch=re.compile(match)
   cmatch=match
   checkmatch=cmatch.search(line)
   if checkmatch!=None:
      print &quot;-----------------------------------------&quot;
      print &quot;Got the line....&quot;+line
      return 0
   else:
      return -1

def readfilestring(filename, match):
   linestring = open(filename, &#39;r&#39;)
   l=linestring.readline()
   while l != &#39;&#39;:
      #print l
      if matchline(l,match) ==0:
         print &quot;&lt;----in file&quot; + filename
         print &quot;-----------------------------------------&quot;
      l=linestring.readline()
      

def search_file(search_path,filename,stringpatt):
   try:
      dirList = os.listdir(search_path)
   except Exception, e:
      print &quot;Search error for OS issue - &quot;
      print e
   else:
      for d in dirList:
         if os.path.isdir(search_path+os.sep+d) == True:
            search_file(search_path+os.sep+d,filename,stringpatt)
         elif os.path.isfile(search_path+os.sep+d) == True:
            #print d + &quot; is a file update whatever required&quot;
            pmatch=filename.search(d)
            if pmatch==None:
               ss=1
            else:
               #print &quot;-----------------------------------------&quot;
               #print &quot;The file is found - &quot;+search_path+os.sep+d
               #print &quot;-----------------------------------------&quot;
               readfilestring(search_path+os.sep+d, stringpatt)
         else:
            print &quot;Unknown filesystem object - &quot;+search_path+os.sep+d
   
if __name__ == &#39;__main__&#39;:
   search_path = raw_input(&quot;Enter search_path: &quot;)
   filepattern = raw_input(&quot;Enter filepattern: &quot;)
   stringpattern= raw_input(&quot;Enter stringpattern: &quot;)
   try:
      retest=&quot;filepattern&quot;
      ire=re.compile(filepattern,re.I)
      retest=&quot;stringpattern&quot;
      strre=re.compile(stringpattern,re.I)
   except Exception, e:
      print &quot;Reg Ex problem - for &quot;+retest
      print e
   else:
      if os.path.exists(search_path):
         find_file = search_file(search_path,ire,strre)
      else:
         print &quot;Not a valid path - &quot;+search_path

&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/3975935212202557837/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/find-textpattern-under-parent-folder.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/3975935212202557837'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/3975935212202557837'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/find-textpattern-under-parent-folder.html' title='Find text/pattern under parent folder from matched file names'/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-7582749898467023098</id><published>2012-10-26T10:35:00.000-07:00</published><updated>2012-10-26T10:35:00.504-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="CSV Examples"/><category scheme="http://www.blogger.com/atom/ns#" term="Python XML Parser"/><title type='text'> XML to CSV Converter</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Python Program to extract each execution data (few children in xml) and create a csv file. 
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
 def xml2csv(inputFile,outputFile,elemName,ns,columnsToExtract):
   outFile=open(outputFile,&#39;w&#39;)
   writer=csv.DictWriter(outFile,columnsToExtract,extrasaction=&#39;ignore&#39;,restval=&#39;&#39;)

   # Write Header to CSV file
   writer.writerow(columnsToExtract)

   #Sree -Used iterparse, so that only partial xml is in memory and after usage every element is cleared out of memory.
   for  event,rec in etree.iterparse(inputFile, tag=&quot;%s%s&quot; %(ns,elemName)):
      row=dict()
      for child in rec:
         row[child.tag[len(ns):]]=child.text.strip()
      rec.clear()
      writer.writerow(row)
      outFile.close()

&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/7582749898467023098/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/xml-to-csv-converter.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/7582749898467023098'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/7582749898467023098'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/xml-to-csv-converter.html' title=' XML to CSV Converter'/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-6112986365600204693</id><published>2012-10-25T10:27:00.000-07:00</published><updated>2012-10-25T10:27:00.067-07:00</updated><title type='text'>XSL to CSV converter  </title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Leaverage python csv writer and xlrd reader to do this job. &lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
def xls2csv(inputFile,outputFile):
   print &quot;Input File : %s&quot; %(inputFile)
   print &quot;Output File : %s&quot; %(outputFile)
   writer=csv.writer(open(outputFile,&#39;w&#39;),delimiter=&#39;,&#39;,quotechar=&#39;&quot;&#39;)
   book=xlrd.open_workbook(inputFile)
   sheet=book.sheet_by_index(0)
   for row in range(sheet.nrows):
      writer.writerow( sheet.row_values(row))
&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/6112986365600204693/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/xsl-to-csv-converter.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/6112986365600204693'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/6112986365600204693'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/xsl-to-csv-converter.html' title='XSL to CSV converter  '/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-8455990239369242257</id><published>2012-10-25T10:22:00.000-07:00</published><updated>2012-10-25T10:22:00.467-07:00</updated><title type='text'>Spell Corrector in Python</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
import re, collections

def words(text): return re.findall(&#39;[a-z]+&#39;, text.lower()) 

def train(features):   
 model = collections.defaultdict(lambda: 1)    
 for f in features:        
  model[f] += 1    
 return model

NWORDS = train(words(file(&#39;big.txt&#39;).read()))
alphabet = &#39;abcdefghijklmnopqrstuvwxyz&#39;

def edits1(word):   
 splits     = [(word[:i], word[i:]) for i in range(len(word) + 1)]   
 deletes    = [a + b[1:] for a, b in splits if b]   
 transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)&gt;1]   
 replaces   = [a + c + b[1:] for a, b in splits for c in alphabet if b]   
 inserts    = [a + c + b     for a, b in splits for c in alphabet]   
 return set(deletes + transposes + replaces + inserts)

def known_edits2(word):    
 return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)

def known(words): return set(w for w in words if w in NWORDS)

def correct(word):    
 candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]    
 return max(candidates, key=NWORDS.get)

&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/8455990239369242257/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/spell-corrector-in-python.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/8455990239369242257'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/8455990239369242257'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/spell-corrector-in-python.html' title='Spell Corrector in Python'/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-1684557296960409459</id><published>2012-10-24T05:03:00.000-07:00</published><updated>2012-10-24T05:03:00.914-07:00</updated><title type='text'> Format a plain ASCII file using Python script </title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Format a plain ASCII file, adding page breaks and line feeds. This is handy for sending output to my dot-matrix printer; under Linux, just do pyprint filename &amp;gt;/dev/lp1 (or to whatever your printer device is).   &lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
#!/bin/env python

# Paginate a text file, adding a header and footer 

import sys, time, string

# If no arguments were given, print a helpful message
if len(sys.argv)!=2:
    print &#39;Usage: pyprint filename&#39;
    sys.exit(0)

class PrinterFormatter:
    def __init__(self, filename, page_len=58): 
 # Save the time of creation for inclusion in the header
 import time
 self.now=time.asctime(time.localtime(time.time()))

 # Save the filename and page length
 self.filename=filename ; self.page_len = page_len
 
 # Zero all the counters
 self.page=0 ; self.count=0 ; self.header_written=0

    def write_header(self):
 # If the header for this page has just been written, don&#39;t
 # write another one.
 if self.header_written: return

 # Increment the page count, and reset the line count
 self.header_written=1 ; self.count=1 ; self.page=self.page+1

 # Write the header
 header=self.filename
 p=str(self.page) ; header=string.ljust(header, 38-len(p))+&#39;[&#39;+p+&#39;]&#39;
 header=string.ljust(header, 79-len(self.now))+self.now
 sys.stdout.write(header+&#39;\n\n&#39;)

    def writeline(self, L):
 # If the line is exactly 80 lines long, chop off any trailing
 # newline, since the printhead will wrap around
        length=len(L)
 if (length % 80) == 0 and L and L[-1]==&#39;\n&#39;: L=L[:-1]

 # If we&#39;ve printed a pageful of lines, output a linefeed and
 # output the header.
 if self.count&gt;self.page_len:
     sys.stdout.write(&#39;&#39;)
     self.write_header()

 # Print the actual line of text
 sys.stdout.write(L) 
 self.count=self.count+1 ; self.header_written=0

# Open the input file, and create a PrinterFormatter object, passing
# it the filename to put in the page header.
    
f=open(sys.argv[1], &#39;r&#39;)
o=PrinterFormatter(sys.argv[1])
o.write_header()   # Print the header on the first page

# Iterate over all the lines in the file; the writeline() method will
# output them and automatically add page breaks and headers where
# required.
while (1):
    L=f.readline()
    if L==&quot;&quot;: break
    o.writeline(L)

# Write a final page break and close the input file.
sys.stdout.write(&#39;&#39;)
f.close()

&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/1684557296960409459/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/format-plain-ascii-file-using-python.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/1684557296960409459'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/1684557296960409459'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/format-plain-ascii-file-using-python.html' title=' Format a plain ASCII file using Python script '/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-8249144474949813391</id><published>2012-10-24T05:00:00.000-07:00</published><updated>2012-10-24T05:00:09.473-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Control Structure"/><title type='text'>Control Structures in Python</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
This Program explains different control structures in python  &lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
If
====
# basic &quot;If&quot;
if boolean:
    x = 1
else:
    x = 0

# Not so basic &quot;If&quot;
# Notice the new keywords!
if (boolean and otherboolean) or ( not boolean ):  #oops, this is just if(boolean), oh well...  :~)
    x = 1
elif not otherboolean:
    x = 0
else:
    x = 100000000000000000000 # Big numbers make if statements less boring!

While
=====

# This is it...  
while i &lt; 100:
    i + 1

# More generally:
while condition == true:
    &quot;&quot;&quot;do the following&quot;&quot;&quot;
    ...
    ...
    condition = false.

# Infinite Loop:
while 1:
    print &quot;I&#39;m loopy!&quot;


FOR
====

# Basic For Loop
for item in list:
    dosomething(item)

# The traditional C for loop has a different form in Python:
for x in range(0, 100):
    dosomething(x)

# More interesting example:
def buglove( UIUC ):
    for bug in UIUC:
        if type( bug ) == type( chinese_lady_beetle() ):
            crush( bug )
        else:
            hug( bug )





&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/8249144474949813391/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/control-structures-in-python.html#comment-form' title='11 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/8249144474949813391'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/8249144474949813391'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/control-structures-in-python.html' title='Control Structures in Python'/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>11</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-5377094815892659378</id><published>2012-10-23T21:30:00.000-07:00</published><updated>2012-10-23T21:30:03.775-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Zip File Example"/><title type='text'>Python script to zip and unzip files</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
# Simple Application/Script to Compress a File or Directory
# Essentially you could use this instead of Winzip

&quot;&quot;&quot;
Path can be a file or directory
Archname is the name of the to be created archive
&quot;&quot;&quot;
from zipfile import ZipFile, ZIP_DEFLATED
import os  # File stuff
import sys # Command line parsing
def zippy(path, archive):
    paths = os.listdir(path)
    for p in paths:
        p = os.path.join(path, p) # Make the path relative
        if os.path.isdir(p): # Recursive case
            zippy(p, archive)
        else:
            archive.write(p) # Write the file to the zipfile
    return

def zipit(path, archname):
    # Create a ZipFile Object primed to write
    archive = ZipFile(archname, &quot;w&quot;, ZIP_DEFLATED) # &quot;a&quot; to append, &quot;r&quot; to read
    # Recurse or not, depending on what path is
    if os.path.isdir(path):
        zippy(path, archive)
    else:
        archive.write(path)
    archive.close()
    return &quot;Compression of \&quot;&quot;+path+&quot;\&quot; was successful!&quot;

instructions = &quot;zipit.py:  Simple zipfile creation script.&quot; + \
               &quot;recursively zips files in a directory into&quot; + \
               &quot;a single archive.&quot; +\
               &quot;e.g.:  python zipit.py myfiles myfiles.zip&quot;

# Notice the __name__==&quot;__main__&quot;
# this is used to control what Python does when it is called from the
# command line.  I&#39;m sure you&#39;ve seen this in some of my other examples.
if __name__==&quot;__main__&quot;:
    if len(sys.argv) &gt;= 3:
        result = zipit(sys.argv[1], sys.argv[2])
        print result
    else:
        print instructions


================================================================================


# Simple script to Unzip archives created by
# our Zip Scripts.

import sys
import os
from zipfile import ZipFile, ZIP_DEFLATED

def unzip( path ):
    # Create a ZipFile Object Instance
    archive = ZipFile(path, &quot;r&quot;, ZIP_DEFLATED)
    names = archive.namelist()
    for name in names:
        if not os.path.exists(os.path.dirname(name)):
            # Create that directory
            os.mkdir(os.path.dirname(name))
        # Write files to disk
        temp = open(name, &quot;wb&quot;) # create the file
        data = archive.read(name) #read the binary data
        temp.write(data)
        temp.close()
    archive.close()
    return &quot;\&quot;&quot;+path+&quot;\&quot; was unzipped successfully.&quot;
    
instructions = &quot;This script unzips plain jane zipfiles:&quot;+\
               &quot;e.g.:  python unzipit.py myfiles.zip&quot;

if __name__==&quot;__main__&quot;:
    if len(sys.argv) == 2:
        msg = unzip(sys.argv[1])
        print msg
    else:
        print instructions

&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/5377094815892659378/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-script-to-zip-and-unzip-files.html#comment-form' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/5377094815892659378'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/5377094815892659378'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-script-to-zip-and-unzip-files.html' title='Python script to zip and unzip files'/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-7631399238222785012</id><published>2012-10-23T04:55:00.000-07:00</published><updated>2012-10-23T04:55:00.568-07:00</updated><title type='text'> Fast and efficient Backup script that works on Windows and Linux </title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
This python script backup your directory structure that works on Linux and Windows both. It directly uses the shell to do this task and shell commands are considered very fast compared to file operations does otherwise.  
 
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
import os, os.path
import subprocess
import time
def backUpDir(path):
    &quot;&quot;&quot;
    Creates backup of the passed old dir and creates a new dir. The backed up dir gets the
    date and time as the name of the new backed up file.
    On success, returns a list consising of two values:
        0: to signify the success
        None: means no error occurred.

    On error, return a list consisting of two values:
        -1 : to signify the failure
        error string: the exact error string
    &quot;&quot;&quot;

    if os.path.exists(path) == True:
        #dir exists then backup old dir and create new
        backupDir = path + time.strftime(&#39;-%Y-%m-%d-%Hh%Mm%Ss&#39;)
        
        if os.name == &quot;nt&quot;:
            #NT Sysyem  - used the DOS Command &#39;move&#39; to rename the folder
            cmd = subprocess.Popen([&quot;mov&quot;, path, backupDir], \
                                    shell = True, \
                                    stdout = subprocess.PIPE, \
                                    stdin = subprocess.PIPE, \
                                    stderr = subprocess.PIPE)
        elif os.name == &quot;posix&quot;:
            #POSIX System - use the appropriate POSIX command to rename the folder.
            cmd=subprocess.Popen([&quot;mv&quot;, path, backupDir], \
                                    shell = True, \
                                    stdout = subprocess.PIPE, \
                                    stdin = subprocess.PIPE, \
                                    stderr = subprocess.PIPE)
            pass
        else:
            # Not supported on other platforms
            return [-1, &quot;Not supported on %s platform&quot; %(os.name)]
        (out, err) = cmd.communicate()
        if len(err) != 0:
            return [-1, err]
        else:
            os.mkdir(path)
            return [0, None]
    else:
        #create new dir
        os.mkdir(path)
        return [0, None]
&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/7631399238222785012/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/fast-and-efficient-backup-script-that.html#comment-form' title='7 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/7631399238222785012'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/7631399238222785012'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/fast-and-efficient-backup-script-that.html' title=' Fast and efficient Backup script that works on Windows and Linux '/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>7</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-5035978045458590052</id><published>2012-10-22T04:53:00.000-07:00</published><updated>2012-10-22T04:53:00.946-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python File Example"/><title type='text'>File Splitter Script </title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
The script would take in the input file with multiple rows and would give a row count. This can then be used to decide on the number of segmented files that would need to be generated based on the required number of rows in each file. Please note that I shall be making a GUI version of the same soon for simplifying use.   &lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
#!/usr/bin/env python
# encoding: utf-8

import sys
from math import *
import os
import random
from Tkinter import *
import tkFileDialog
 

def linesplit():
        line=0
        k1=tkFileDialog.askopenfilename()
        ff=open(k1)
        for lineee in ff:
                line=line+1
        print &quot;total number of lines is:&quot;+str(line)
        ff.close()
        line=0
        user_ask=raw_input(&quot;Specify the number of records in each file = &quot;)
        user_ask=eval(user_ask)
        print user_ask
        ff=open(k1)
        i=1
        temp=user_ask
        for lineee in ff:
                line=line+1
                temp_filename=&quot;c:\Temp\split_&quot;+str(i)+&quot;.txt&quot;
                if(line &lt; user_ask):
                        ff1=open(temp_filename,&#39;a+&#39;)
                        ff1.write(lineee)
                        ff1.close()
                if(line == user_ask):
                        user_ask=user_ask+temp
                        i=i+1
                        
        ff.close()
        flag=1
        return (line,flag)


k=linesplit()
flag=k[1]

&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/5035978045458590052/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/file-splitter-script.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/5035978045458590052'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/5035978045458590052'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/file-splitter-script.html' title='File Splitter Script '/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-6138144825732220590</id><published>2012-10-22T04:49:00.000-07:00</published><updated>2012-10-22T04:49:00.577-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Searching Example"/><title type='text'>Python script for walking the directory tree structure but excluding some directories and files </title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
The script walks the directory structure recursively. Some of the directories and files can be excluded from the walk by providing them in an exclude_list  
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
def walkExclusive(top, topdown=True,
onerror=None, exclude_list=[]):&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    &quot;&quot;&quot;Directory tree
generator.&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    For each directory in the directory
tree rooted at top (including top&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    itself, but excluding &#39;.&#39; and
&#39;..&#39;), yields a 3-tuple&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
        dirpath, dirnames, filenames&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    dirpath is a string, the path to
the directory.  dirnames is a list of&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    the names of the subdirectories in
dirpath (excluding &#39;.&#39; and &#39;..&#39;).&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    filenames is a list of the names of
the non-directory files in dirpath.&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    Note that the names in the lists
are just names, with no path components.&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    To get a full path (which begins
with top) to a file or directory in&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    dirpath, do os.path.join(dirpath,
name).&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    If optional arg &#39;topdown&#39; is true
or not specified, the triple for a&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    directory is generated before the
triples for any of its subdirectories&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    (directories are generated top
down).  If topdown is false, the triple&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    for a directory is generated after
the triples for all of its&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    subdirectories (directories are
generated bottom up).&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    When topdown is true, the caller
can modify the dirnames list in-place&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    (e.g., via del or slice
assignment), and walk will only recurse into the&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    subdirectories whose names remain
in dirnames; this can be used to prune&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    the search, or to impose a specific
order of visiting.  Modifying&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    dirnames when topdown is false is
ineffective, since the directories in&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    dirnames have already been
generated by the time dirnames itself is&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    generated.&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    exclude_list is a list containing
items which are not to be walked in the&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    directory structure. e.g.
exclude_list = [&#39;.svn&#39;, &#39;.project&#39;]&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    By default errors from the
os.listdir() call are ignored.  If&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    optional arg &#39;onerror&#39; is
specified, it should be a function; it&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    will be called with one argument,
an os.error instance.  It can&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    report the error to continue with
the walk, or raise the exception&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    to abort the walk.  Note that the
filename is available as the&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    filename attribute of the exception
object.&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    Caution:  if you pass a relative
pathname for top, don&#39;t change the&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    current working directory between
resumptions of walk.  walk never&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    changes the current directory, and
assumes that the client doesn&#39;t&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    either.&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
    Example:&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
 from os.path import join, getsize
    for root, dirs, files in walk(&#39;python/Lib/email&#39;):
        print root, &quot;consumes&quot;,
        print sum([getsize(join(root, name)) for name in files]),
        print &quot;bytes in&quot;, len(files), &quot;non-directory files&quot;
        if &#39;CVS&#39; in dirs:
            dirs.remove(&#39;CVS&#39;)  # don&#39;t visit CVS directories
    &quot;&quot;&quot;

    from os.path import join, isdir, islink
    from os import error, listdir
    
    # We may not have read permission for top, in which case we can&#39;t
    # get a list of the files the directory contains.  os.path.walk
    # always suppressed the exception then, rather than blow up for a
    # minor reason when (say) a thousand readable directories are still
    # left to visit.  That logic is copied here.
    try:
        # Note that listdir and error are globals in this module due
        # to earlier import-*.
        names = listdir(top)
    except error, err:
        if onerror is not None:
            onerror(err)
        return
    
    if exclude_list != []:
        from copy import deepcopy
        temp_name = deepcopy(names)
        names = [item for item in temp_name if item not in exclude_list]
        
    dirs, nondirs = [], []
    for name in names:
        if isdir(join(top, name)):
            dirs.append(name)
        else:
            nondirs.append(name)

    if topdown:
        yield top, dirs, nondirs
    for name in dirs:
        path = join(top, name)
        if not islink(path):
            for x in walkExclusive(path, topdown, onerror, exclude_list):
                yield x
    if not topdown:
        yield top, dirs, nondirs

&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/6138144825732220590/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-script-for-walking-directory.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/6138144825732220590'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/6138144825732220590'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-script-for-walking-directory.html' title='Python script for walking the directory tree structure but excluding some directories and files '/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-2497457451825408615</id><published>2012-10-21T17:30:00.000-07:00</published><updated>2012-10-21T17:30:02.538-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python XML Parser"/><title type='text'>Python XML Parser</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
In our project we had kept the
operations rules as an XML and the below mentioned parser was used to
get the conditions to be applied for each operation. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
The xml.dom.minidom was used to parse
the xml file and return a document object .The document object was
used to obtain the child nodes and for each child nodes the
corresponding fileds and attributes were retrieved using the get
attribute method and appended as a tuple. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
The tuple was then included in the
dictionary with the nodename as the key. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;

&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
 import xml.dom.minidom

class XMLParser:
    def __init__(self, filePath):
        self.xml_file_path = filePath

    def get_a_document(self):
        return xml.dom.minidom.parse(self.xml_file_path)

    def process_xml_return_dict(self):
        doc = self.get_a_document()
        fieldMapping = doc.childNodes[0]
        operations = {}
        for layer in fieldMapping.childNodes:
            if layer.nodeType == xml.dom.minidom.Node.TEXT_NODE or layer.nodeType == xml.dom.minidom.Node.COMMENT_NODE:
                continue
            fieldList = self.get_fields(layer)
            attrList = self.get_attributes(layer)
            operations[layer.nodeName] = (attrList, fieldList)
        return operations

    def get_attributes(self, node):
        attrList = []
        nodeMap = node.attributes
        for index in range(nodeMap.length):
            attrName = nodeMap.item(index).name
            attrValue = node.getAttribute(attrName)
            attrList.append((attrName, attrValue))
        return attrList

    def get_fields(self, node):
        fieldList = []
        for childNode in node.childNodes:
            if childNode.nodeType != xml.dom.minidom.Node.TEXT_NODE and childNode.nodeType != xml.dom.minidom.Node.COMMENT_NODE:
                fromField = childNode.getAttribute(&#39;FromField&#39;)
                toField = childNode.getAttribute(&#39;ToField&#39;)
                fieldValue = childNode.getAttribute(&#39;Value&#39;)
                condition = childNode.getAttribute(&#39;Condition&#39;)
                fieldList.append((fromField, toField, fieldValue, condition))
        return fieldList
Python pickle module &amp; Zip file creation
 
Description
The solution gives a solution to use the pickle module and to create a Zip File.  
 
 # below is a typical Python dictionary object of roman numerals
 romanD1 = {&#39;I&#39;:1,&#39;II&#39;:2,&#39;III&#39;:3,&#39;IV&#39;:4,&#39;V&#39;:5,&#39;VI&#39;:6,&#39;VII&#39;:7,&#39;VIII&#39;:8,&#39;IX&#39;:9,&#39;X&#39;:10}
  
 # to save a Python object like a dictionary to a file
 # and load it back intact you have to use the pickle module
 import pickle
 print &quot;The original dictionary:&quot;
 print romanD1
 file = open(&quot;roman1.dat&quot;, &quot;w&quot;)
 pickle.dump(romanD1, file)
 file.close()
 # now load the dictionay object back from the file ...
 file = open(&quot;roman1.dat&quot;, &quot;r&quot;)
 romanD2 = pickle.load(file)
 file.close()
 print &quot;Dictionary after pickle.dump() and pickle.load():&quot;
 print romanD2

 # for large text files you can write and read a zipped file (PKZIP format)
 # notice that the syntax is mildly different from normal file read/write
 import zipfile
 zfilename = &quot;English101.zip&quot;
 zout = zipfile.ZipFile(zfilename, &quot;w&quot;)
 zout.writestr(zfilename, str1 + str2)
 zout.close()
 # read the zipped file back in
 zin = zipfile.ZipFile(zfilename, &quot;r&quot;)
 strz = zin.read(zfilename)
 zin.close()
 print &quot;Testing the contents of %s:&quot; % zfilename
 print strz
&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/2497457451825408615/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-xml-parser.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/2497457451825408615'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/2497457451825408615'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-xml-parser.html' title='Python XML Parser'/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-1275039909739225482</id><published>2012-10-21T04:39:00.000-07:00</published><updated>2012-10-21T04:39:00.295-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python Network Example"/><title type='text'>IP Address Generation</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
The script asks the user for two IP
addresses . One is the start of the IP range, and the second is the
end of it. Next, a new IP object is created using the defined IP
class called i . The final step before generating the IPs is to
initialize the file the IP addresses will be written to, named ofile
. Now the fun begins. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
For each item returned, the results
will be output to ofile. Using the IP class method succ!, an until
loop calls the succ! method until i equals end_ip . Once the two
values are equal, that means the ending IP address has been generated
and the output file is closed. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
The script relies on a custom class
called IP, which has four methods: initialize, to_s, succ, and succ!.
The IP class is important because, once an object is created, the IP
address is stored as a class variable for easy tracking. The first
method called, when i is declared, is initialize. This sets @ip to
start_ip . Next, succ! is called to begin creating the range of IPs.
succ! calls succ and utilizes the replace method to overwrite the
contents in @ip whenever succ returns a value . The meat of the IP
class is located in the method succ . If @ip ever increments to the
highest IP address, the script will return 255.255.255.255. IP
addresses can only go up to that value. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Next, the IP address, stored in @ip, is
split apart in reverse order, using the period as a delimiter. The
values are stored in an array called parts. After the IP address is
properly separated, a new code block is called on the array using the
each_with_index method to access two pieces of informationâ??the
index being passed and the value . Within this block, the value in
part is compared against 255, again to prohibit invalid IP addresses.
If the value is equal to 255, then it is reset to zero . The one
exception to the zero reset is if the value of i is equal to 3, since
that is the first octet of the IP. If part is less than 255, the
method succ! is called and the if/else statement breaks. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
After each part has been run through
the code block, the IP address is put back together opposite of how
it was taken apart. The script puts each piece back together using
the join method, with periods in between the elements, all in reverse
order . As mentioned previously, the succ! method is called until the
end_ip address is equal to the results of succ!. That&#39;s all there is
to perfectly generating an IP address range. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
class IP
     def initialize(ip)
         @ip = ip
     end

     def to_s
         @ip
     end

     def==(other)
         to_s==other.to_s
     end

     def succ
         return @ip if @ip == &quot;255.255.255.255&quot;
         parts = @ip.split(&#39;.&#39;).reverse
         parts.each_with_index do |part,i|
             if part.to_i &lt; 255
                 part.succ!
                 break
             elsif part == &quot;255&quot;
                 part.replace(&quot;0&quot;) unless i == 3
             else
                 raise ArgumentError, &quot;Invalid number #{part} in IP address&quot;
             end
         end
         parts.reverse.join(&#39;.&#39;)
     end

     def succ!
         @ip.replace(succ)
     end
 end

 print &quot;Input Starting IP Address: &quot;
 start_ip = gets.strip 

 print &quot;Input Ending IP Address: &quot;
 end_ip = gets.strip

 i = IP.new(start_ip)

 ofile = File.open(&quot;ips.txt&quot;, &quot;w&quot;)
 ofile.puts i.succ! until i == end_ip
 ofile.close

&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/1275039909739225482/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/ip-address-generation.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/1275039909739225482'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/1275039909739225482'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/ip-address-generation.html' title='IP Address Generation'/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-385557853437816833</id><published>2012-10-20T21:30:00.000-07:00</published><updated>2012-10-20T21:30:01.300-07:00</updated><title type='text'>Orphan Checker </title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
The script does not use any outside
libraries, thus keeping its execution simple. we will start by initializing
the arrays that we&#39;ll be using to keep track of our links and orphan
files . Next, we look to ensure that our links.txt file exists. If not,
then there isn&#39;t much point in continuing to run the script, so it
exits out with a nice error message . If links.txt does exist, then
we continue by opening the file and reading in all of the contents
line-by-line. You can change this to a comma-separated values (CSV)
file, but I prefer the readability of one link per line. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
After the links have been stored in the
array links, the script begins to index every file in the current
working directory. The results will be stored in an array called
orphans . If there are subdirectories, the script will also index
those files. Presumably, you would run this in the root directory of
your web server to take full advantage of this script. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Now that the script has both the links
and local files indexed, it is time to start comparing the two
arrays, and see what&#39;s left . I called the second array orphans
because I will be deleting any entry that exists within the link
array. Whatever is left will be files not included on the
public-facing side of the web server. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
The script ends by creating a file
called orphans.txt in the script&#39;s directory and writing the results
to that file . Finally, after the code block is finished, the file is
closed and the script finished. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
links = Array.new
 orphans = Array.new
 dir_array = [Dir.getwd]

 unless File.readable?(&quot;links.txt&quot;)
     puts &quot;File is not readable.&quot;
     exit
 end

 File.open(&#39;links.txt&#39;, &#39;rb&#39;) do |lv|
     lv.each_line do |line|
         links &lt;&lt; line.chomp
     end
 end

 begin
     p = dir_array.shift 
     Dir.chdir(p)

     Dir.foreach(p) do |filename|
         next if filename == &#39;.&#39; or filename == &#39;..&#39;
         if !File::directory?(filename)
                orphans &lt;&lt; p + File::SEPARATOR + filename
         else
             dir_array &lt;&lt; p + File::SEPARATOR + filename
         end
     end
 end while !dir_array.empty?

 orphans -= links

 File.open(&quot;orphans.txt&quot;, &quot;wb&quot;) do |o|
       o.puts orphans
 end

&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/385557853437816833/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/orphan-checker.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/385557853437816833'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/385557853437816833'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/orphan-checker.html' title='Orphan Checker '/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-3758990845093873179</id><published>2012-10-20T10:26:00.000-07:00</published><updated>2012-10-20T10:26:39.696-07:00</updated><title type='text'>HTML Email using Python</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
We created a module called sendmail which email html content. Each of application dumps data from the datastructure into html format and then calls this module  &lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
def createhtmlmail( html, text, subject ):
   &quot;&quot;&quot;Create a mime-message that will render HTML in popular
      MUAs, text in better ones&quot;&quot;&quot;
   import MimeWriter
   import mimetools
   import cStringIO

   out = cStringIO.StringIO() # output buffer for our message
   htmlin = cStringIO.StringIO(html)

   writer = MimeWriter.MimeWriter(out)
#
# set up some basic headers... we put subject here
# because smtplib.sendmail expects it to be in the
# message body
#
   
   writer.addheader(&quot;Subject&quot;, subject)
   writer.addheader(&quot;MIME-Version&quot;, &quot;1.0&quot;)
#
# start the multipart section of the message
# multipart/alternative seems to work better
# on some MUAs than multipart/mixed
#
   writer.startmultipartbody(&quot;alternative&quot;)
   writer.flushheaders()
#
# the plain text section
#
   if text != None:
      txtin = cStringIO.StringIO(text)
      subpart = writer.nextpart()
      subpart.addheader(&quot;Content-Transfer-Encoding&quot;, &quot;quoted-printable&quot;)
      pout = subpart.startbody(&quot;text/plain&quot;, [(&quot;charset&quot;, &#39;us-ascii&#39;)])
      mimetools.encode(txtin, pout, &#39;quoted-printable&#39;)
      txtin.close()
#
# start the html subpart of the message
#
   subpart = writer.nextpart()
   subpart.addheader(&quot;Content-Transfer-Encoding&quot;, &quot;quoted-printable&quot;)
#
# returns us a file-ish object we can write to
#
   pout = subpart.startbody(&quot;text/html&quot;, [(&quot;charset&quot;, &#39;us-ascii&#39;)])
   mimetools.encode(htmlin, pout, &#39;quoted-printable&#39;)
   htmlin.close()
#
# Now that we&#39;re done, close our writer and
# return the message body
#
   writer.lastpart()
   msg = out.getvalue()
   out.close()
   #print msg
   return msg

def sendmail (sender,to,subject,htmlFilename):
   import smtplib
   f = open(htmlFilename, &#39;r&#39;)
   html = f.read()
   f.close()
   message = createhtmlmail(html, None, subject)
   server = smtplib.SMTP(&quot;mta-hub&quot;)
   server.sendmail(sender, to, message)
   server.quit()

&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/3758990845093873179/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/html-email-using-python.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/3758990845093873179'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/3758990845093873179'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/html-email-using-python.html' title='HTML Email using Python'/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-50289444731520985</id><published>2012-10-20T04:26:00.000-07:00</published><updated>2012-10-20T04:26:00.303-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Command Execution Using Python"/><title type='text'>Python interface to load commands. </title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
In a way to standardise commands this
approach uses a config file approach , which contains the system
commands . usage: 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
The user creates a command file which
lists commands with parameters as %s. a typical command file contains
the following lines for a copy command. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
CP_CMD=cp %s %s 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
now when I call the create_command
function 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
cmd_str=create_command(&quot;/dir1&quot;,&quot;/dir2&quot;,&quot;CP_CMD&quot;)
the cmd_str contains cp /dir1 /dir2 , which can be eventually
executed. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
The command file can contain hundreds
of commands listed one below the other as follows 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
CP_CMD=cp %s %s 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
FTP_CMD=ftp %s 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
DIR_CMD=dir %s 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
This is just a code snippet elaborating
the idea. Adding features like exceptions, Fancier formatting , Error
redirection etc is left to you !&lt;/blockquote&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
&quot;&quot;&quot; This Function loads a command file into memory as a dictonary , With Commands as keys&quot;&quot;&quot;
def load_command_file(file_name):
 command_dict={}
 if file_name.isalpha():
  print(&quot;Error!!command file name should be in ascii\n&quot;);
  return command_dict
 file=open(file_name,&#39;r&#39;)
 file_lines=file.readlines()
 for line in file_lines:        
  command_list=line.strip().split(&quot;=&quot;)
  command_dict[command_list[0].strip()]=command_list[1].strip()
 file.close()    
 return command_dict

########################################################################################################

&quot;&quot;&quot; This function uses the above mentioned methods to create commands based on passed args&quot;&quot;&quot; 
def create_command(*args):
 command_dict=load_command_file(r&quot;C:\Documents and Settings\Raj\Desktop\command_file.txt&quot;)
#print(command_dict)
 arg_len=len(args)
 command_str=command_dict[args[arg_len-1]]
 if command_str.count(&#39;%s&#39;)!=arg_len-1:
  print(&quot;Error mismatch in args passed and args actually needed&quot;)
  sys.exit() 
 command=command_str%(args[:-1])
 return command

&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/50289444731520985/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-interface-to-load-commands.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/50289444731520985'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/50289444731520985'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-interface-to-load-commands.html' title='Python interface to load commands. '/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-7635871469694907774</id><published>2012-10-19T04:20:00.000-07:00</published><updated>2012-10-19T04:20:00.247-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python Date Example"/><title type='text'>Python script to Validate Tabular format Data and database restore  </title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
Our python utility does all these functionality.&lt;br /&gt;
&lt;br /&gt;
Major functionality:&lt;br /&gt;
&lt;br /&gt;
&lt;ul style=&quot;text-align: left;&quot;&gt;
&lt;li&gt;Process a batch of large cvs/text files&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Can iterate in sub-folders&amp;nbsp;&lt;/li&gt;
&lt;li&gt;File can be filtered on criteria expressed in regular expression format&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Reading cvs/text files&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Performing sanity and basic column based validation checks like null values, duplicate values, max, min, unique values etc.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;It also infer data type for all columns&amp;nbsp;&lt;/li&gt;
&lt;li&gt;SQL Server connection&amp;nbsp;&lt;/li&gt;
&lt;li&gt;On the fly table creation and bulk insertion for any given text/cvs file&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Logging of all activities using a separate logger module&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Highly configured utility&amp;nbsp;&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
Main.py:
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;import Utility
import Logger
import FieldTypes
import SQLServerConnection

import datetime
import os
import re
import string
import pyodbc


#start time
Logger.LogMessage(str(datetime.datetime.now()))
dbConn = SQLServerConnection();
temp = Utility()

#read source directory
reader = open(&quot;srcdir.txt&quot;,&quot;rb&quot;)
srcdir = reader.readline()

iterate source directory
temp.iterateFolder(srcdir)
temp.reportProfile()
print &quot;profiling done&quot;

reader.close();

#end time
Logger.LogMessage(str(datetime.datetime.now()))
print datetime.datetime.now()

&lt;/pre&gt;
&lt;br /&gt;
Utility.py
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;import SQLServerConnection
import Field
import csv
import os
import re
import string
from Logger import Logger
import datetime



class Utility:
    fileName = &quot;&quot;
    
   
    def __init__(self):
        #initialise class variable
        
        #map for fieldName -&amp;gt; fieldInformation
        self.data = dict()
        self.profileOutput = open(&#39;C:\\temp\\profile.csv&#39;,&#39;w&#39;)
        self.output = [&#39;FileName&#39;,&#39;FieldName&#39;,&#39;InferredDataType&#39;,&#39;Len&#39;,&#39;TotalRows&#39;,&#39;NullValues&#39;,&#39;UniqueValues&#39;]
        self.profileOutput.write(&#39;,&#39;.join(self.output))
        self.profileOutput.write(&#39;\n&#39;)
        self.profileList = []
        
        
    def readcvsFile(self, fileName, onlyName):
        ROWSEPARATER = &quot;\n&quot;
        FIELDSEPARATER = &quot;\t&quot;
        self.data = dict()
        
        #read as a text file
        reader = open(fileName,&quot;rb&quot;)
        headers = reader.readline().split(FIELDSEPARATER)

        #header row
        Column = len(headers)
       
        #initialised the map
        for column in headers:
            self.data[column]=Field.Field(column.rstrip())
        Logger.LogMessage(&quot;No of column:        &quot; + str(Column))
        
        #process every row
        RowCount = 0
        ErrorRow = 0
        for rowstring in reader:
            RowCount = RowCount + 1
            rowCol = rowstring.count(FIELDSEPARATER) + 1
            row = rowstring.split(FIELDSEPARATER)
            #need to check value of last col
            #if it has &quot;,&quot; it means there are more delimiter in text file
            if rowCol == Column:
                i =0
                for column in row:
                    (self.data[headers[i]]).addValue(column)
                    i = i + 1
            else:
                Logger.LogMessage(&quot;Row number &quot; + str(RowCount) + &quot; is not valid. It has &quot; + str(rowCol) + &quot; columns.&quot;)
                ErrorRow = ErrorRow + 1
                   
        Logger.LogMessage(&quot;No of Rows processed(Other than header file):&quot;+str(RowCount))
        Logger.LogMessage(&quot;Total Errors:                                &quot;+str(ErrorRow))
        reader.close();
        
        
        name, extention = onlyName.split(&quot;.&quot;)
        createFile = &quot;create table &quot; +  name + &quot;(&quot;
        fieldCount = 1
        
        for k,v in self.data.iteritems():
            #mark end of processing and take profiled output for each field
            v.endOfLoading()
            self.profileList.append([fileName, v.FieldName, v.FieldString, str(v.FieldSize), str(v.RecordSize), str(v.NullValues), str(v.UniqueValues)])
            if fieldCount &amp;gt; 1:
                createFile = createFile + &quot;, &quot;
            createFile = createFile + v.FieldName + &quot; varchar(1000) &quot;
            
            fieldCount = fieldCount + 1
            v.clear()

        createFile = createFile + &quot;)&quot;
        Logger.LogMessage(&quot;Sql for file creation:&quot; + createFile)
        SQLServerConnection.cursor.execute(createFile)
        SQLServerConnection.conn.commit()
        
        bulkcopySQL = &quot;BULK INSERT &quot; + name + &quot; FROM &#39;&quot; + fileName + &quot;&#39; WITH ( FIELDTERMINATOR=&#39;\t&#39;,FIRSTROW=2,ROWTERMINATOR=&#39;&quot; + chr(10) + &quot;&#39;)&quot;
        Logger.LogMessage(&quot;running bluk copy:&quot; + bulkcopySQL)
        SQLServerConnection.cursor.execute(bulkcopySQL)
        SQLServerConnection.conn.commit()
        
        del self.data
        
        

    def iterateFolder(self,dir):
        fileexp = re.compile(r&#39;\w*\.csv&#39;)
        
        #iterate for the directory
        for f in os.listdir(dir):
            
            if os.path.isfile(os.path.join(dir,f)) and fileexp.match(f) is not None:
                Logger.LogMessage(&quot;***************************************&quot;)
                Logger.LogMessage(&quot;FileName:             &quot; + f)
                Logger.LogMessage(&quot;Directory Name:      &quot; + dir)
                self.readcvsFile(os.path.join(dir,f), f)
                Logger.LogMessage(&quot;*************************************&quot;)
                Logger.LogMessage(str(datetime.datetime.now()))
                Logger.LogMessage(&quot; &quot;)
                print &quot;Processing &quot; , f
               
            
                
                Logger.flush()
            elif os.path.isdir(os.path.join(os.getcwd(),f)): 
                print os.path.join(dir,f)
                self.iterateFolder(os.path.join(dir,f))
          
                
    
    def reportProfile(self):
        
        for detail in self.profileList:
            self.profileOutput.write(&#39;,&#39;.join(detail))
            self.profileOutput.write(&#39;\n&#39;)
            
&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;
Field.py:
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;from types import *
import re
import datetime
import Logger

class FieldTypes:
    Null,Integer, Float, Varchar, Date, DateTime = range(6)
    intexp = re.compile(&#39;[0-9]+$&#39;)
    floatexp = re.compile(&#39;[0-9]*\.[0-9]+$&#39;)
    dateexp = re.compile(r&#39;[0-9]{1,4}([.,/-])[0-9]{1,2}\1[0-9]{1,4}$&#39;)
    
    
     #this functions returns corresponding string for enum type 
    def getEnumString(self, type):
        if type == self.Integer: 
            return &quot;Integer&quot;
        if type is self.Float:
            return &quot;numeric&quot;
        if type is self.Varchar:
            return &quot;varchar&quot;
        if type is self.Date:
            return &quot;date&quot;
        if type is self.Null:
            return &quot;null&quot;
    

 #this function infers datatype using combination of new value and calculated datatype so far    
    def fieldType(self,value, previousType):

        if len(value) is 0:
            return previousType
        
        if previousType is self.Float:
            if self.floatexp.match(value) is not None:
                return self.Float
            
        if previousType is self.Date:
            if self.dateexp.match(value) is not None:
                return self.Date
            
        if previousType is self.Null:
            if self.intexp.match(value) is not None: 
                return self.Integer
            if self.floatexp.match(value) is not None:
                return self.Float
            if self.dateexp.match(value) is not None:
                return self.Date
            
        if previousType is self.Integer:
            if self.intexp.match(value) is not None: 
                return self.Integer
            if self.floatexp.match(value) is not None:
                return self.Float
            if self.dateexp.match(value) is not None:
                return self.Date

        return self.Varchar
            
          
    def getFieldType(self,valueList):
        Type = self.Null
        for value in valueList:
            if Type is self.Varchar:
                break
            Type = self.fieldType(value, Type)
        del valueList
        return Type
            

#Field class represent a complete field domain in the table. It has all properties
#related to a field like name, datatype, size, min value etc. It has contains all 
#list of values for that particular field.
class Field:
   
    def __init__(self, name, storeValue=0):
        self.FieldName = name
        self.FieldSize = 0
        self.FieldType = FieldTypes.Null
        self.FieldValues = set()
        self.RecordSize = 0
        self.UniqueValues = 0
        self.FieldString = &quot;&quot;
        self.NullValues = 0
        self.storeVal = storeValue
       
    def addValue(se1lf,val):
        
        self.RecordSize = self.RecordSize +1
        #print self.FieldValues
        if len(val) is 0:
            self.NullValues = self.NullValues + 1
        else:
            if self.storeVal is not 0:
                self.FieldValues.add((val.rstrip()))
            if len(val) &amp;gt; self.FieldSize:
                self.FieldSize = len(val)
        
    def clear(self):
        del self.FieldValues

    
    def endOfLoading(self):
        if self.storeVal is not 0:
            self.FieldType = FieldTypes().getFieldType(self.FieldValues)
            self.UniqueValues = len(self.FieldValues)
            self.FieldString = FieldTypes().getEnumString(self.FieldType)
        
    def printSummary(self):
        Logger.LogMessage(self.FieldName + &quot; &quot; +  self.FieldString+ &quot; &quot; +str(self.FieldSize)+ str(self.RecordSize)+ str(self.NullValues)+ str(self.UniqueValues)) 
        
    def printValues(self):
        for value in self.FieldValues:
            print value
            
&lt;/pre&gt;
&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/7635871469694907774/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-script-to-validate-tabular.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/7635871469694907774'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/7635871469694907774'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-script-to-validate-tabular.html' title='Python script to Validate Tabular format Data and database restore  '/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-5243378501960764955</id><published>2012-10-19T04:13:00.000-07:00</published><updated>2012-10-19T04:13:00.550-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python File Example"/><title type='text'>Python script to Load Configuration file content into variable </title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Module Name : LoadCfg 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Parameters : Input File 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Output : Dictionary Variable with all
the configuration values in organised way 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Configuration File Format 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
----------------------------------- 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
config.ini 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
PARAM1 = VALUE1 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
PARAM2 = VALUE2 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
. 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Example: 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Cricket_config.ini 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Captain = Dhoni 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Vice Captain = Shewag 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Coach = Gary Kristen 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Team = India 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
teamInfo =
LoadCfg(&quot;Cricket_config.ini&quot;) 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
teamInfo[&quot;Captain&quot;] will Give
Dhoni 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
teamInfo[&quot;Team&quot;] will Give
India  
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
def LoadCfg(filename):
   result=[]
   fileptr = open(filename,&quot;r&quot;)
   for line in fileptr:
        spt_str=line.split(&quot;=&quot;)
        spt_str[0]= spt_str[0].strip()
        spt_str[1]= spt_str[1].strip(&#39;\n&#39;)
        spt_str[1]= spt_str[1].strip()
        spt_str[1]= spt_str[1].strip(&#39;&quot;&#39;)
        result.append(spt_str)
   fileptr.close()
   return dict(result)
&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/5243378501960764955/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-script-to-load-configuration.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/5243378501960764955'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/5243378501960764955'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-script-to-load-configuration.html' title='Python script to Load Configuration file content into variable '/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-1572118548329842361</id><published>2012-10-18T17:30:00.000-07:00</published><updated>2012-10-18T17:30:02.027-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python File Example"/><category scheme="http://www.blogger.com/atom/ns#" term="Searching Example"/><title type='text'>Python Script to search file for specific content</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Module : SearchFile 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Parameters : input file , string to be
searched 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
output : 1 - &amp;gt; if the string founds
inside the file , 0 -&amp;gt; if the string doesnot present in the file 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
This Modules opens the input file and
scan line by line for the specified string . If the particular string
is found, the module returns 1. If the particular string is not found
it returns 0 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Example: 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
if cricket.txt file contains 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Sachin 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Shewag 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
Dhoni 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
SearchFile(&quot;cricket.txt&quot;,&quot;Sachin&quot;)
will return 1 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
SearchFile(&quot;cricket.txt&quot;,&quot;Sania&quot;)
will return 0 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
The key needs to be searched is case
sensitive, 
&lt;/div&gt;
&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
SearchFile(&quot;cricket.txt&quot;,&quot;sachin&quot;)
will return 0 &amp;nbsp;&amp;nbsp;&lt;/div&gt;
&lt;br /&gt;

&lt;div style=&quot;margin-bottom: 0in;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
def SearchFile(filename,key):
   fileptr =  open(filename, &quot;r&quot;)
   for line in fileptr:
      if string.find(line,key) &gt;=0 :
            fileptr.close()
            return 1
   fileptr.close()
   return 0

&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/1572118548329842361/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-script-to-search-file-for.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/1572118548329842361'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/1572118548329842361'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-script-to-search-file-for.html' title='Python Script to search file for specific content'/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-8935476909302961110</id><published>2012-10-18T04:06:00.000-07:00</published><updated>2012-10-18T04:06:00.586-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python File Example"/><title type='text'>Network Wise File Concatenation</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
This is the python script to concatenate the files by network wise. It will consider the first file as destination file and append the content of second file to destination and so on ... until the size of the destination file exceeds the value( configurable) and moves the distnation file into some other location and deletes the source files.  
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;

#!/usr/bin/env python

import sys, os, fnmatch, re
from threading import Thread
from threading import BoundedSemaphore

pool_sema = BoundedSemaphore(value=20)  # only 10 can run at a time

maxsize = 200    # 10 lines for testing

source_directory = &quot;/ranger/RangerRoot/RangerData/CDRDelegatorData/&quot;
destination_directory = &quot;/ranger/RangerRoot/RangerData/CDRDelegatorDataPerf/&quot;
log_directory = &quot;/ranger/RangerRoot/LOG/&quot;
Success_Directory = &quot;/ranger/RangerRoot/RangerData/CDRDelegatorData/success/&quot;
Success_Directory_Perf = &quot;/ranger/RangerRoot/RangerData/CDRDelegatorDataPerf/success/&quot;

filters = []
os.system(&#39;date&#39;)
for i in range(1, 24):
    filters.append(&quot;%02d*&quot; % i)
filters.append(&quot;90*&quot;)
print filters

def fnumlines(filename):
    f = open(filename)
    return f.read().count(&quot;\n&quot;)

class PROCESS(Thread):
    def __init__(self, filelist, pool_sema, network_id):
        Thread.__init__(self)
        self.list = filelist
        self.pool_sema = pool_sema
 self.network_id = network_id

    def run(self):
        self.pool_sema.acquire()
 filename = self.list[0]
 PerfSuccessFile = filename
        logFile = re.sub(&quot;[*]&quot;,&quot;&quot;,self.network_id) + &quot;CDRDelegatorConcatenation.log&quot;
        LogFullName = os.path.join(log_directory, logFile)
        log = open ( LogFullName ,&quot;a&quot;)
        file = os.path.join(source_directory, filename)
 os.system(&#39;cp %s /ranger/ravi/subscriber/&#39; % (file))
 rm_success = os.path.join(Success_Directory,filename)
 filename = file
 touch_Perf = os.path.join(Success_Directory_Perf, PerfSuccessFile )
 numlines = fnumlines(file)
 try:
           f = open(file, &quot;a&quot;)
           for filename_temp in self.list[1:]:
                file = os.path.join(source_directory, filename_temp)
  os.system(&#39;cp %s /ranger/ravi/subscriber/&#39; % (file))
  rm_success_file = os.path.join(Success_Directory, filename_temp)
                log_file = self.network_id + &quot;date.log&quot;
                log_date = os.path.join(log_directory, log_file)
                if numlines &lt; maxsize:
                        try:
                                os.system(&#39;date &gt; %s&#39; % ( log_date))
                                log.write(open(log_date).read())
                                log.write(&quot;%s is concatenating to %s  \n &quot; % (file,filename))
                        except IOError:
                                log.write(&quot;Error: can\&#39;t find file or write the data \n&quot;)
                        try:
                                f.write(open(file).read())
                        except IOError:
                                os.system(&#39;date &gt; %s&#39; % ( log_date ))
                                log.write(open(log_date).read())
                                log.write(&quot;Error occured while reading the file %s \n&quot; % (file))
                        else:
                                log.write(&quot;%s has been concatenated to %s ... DONE\n&quot; % (file,filename))

                        numlines += fnumlines(file)
                        os.system(&#39;rm %s&#39; %(file) )
   os.system(&#39;rm %s&#39; %(rm_success_file))
                else:
                        f.close()
                        # move the file filename
                        
   os.system(&#39;mv %s %s&#39; %(filename, destination_directory))
   touch_Perf = os.path.join(Success_Directory_Perf, PerfSuccessFile)
   touch_file = open(touch_Perf,&quot;w&quot;)
   print touch_Perf
                 touch_file.close()
   PerfSuccessFile = filename_temp
   os.system(&#39;rm %s&#39; % (rm_success))
                        # Use a new file
                        filename = os.path.join(source_directory, file)
   rm_success = rm_success_file
                        numlines = fnumlines(file)
                        f = open(file, &quot;a&quot;)
   filename = file
 finally:
    f.close()
    log.close()
       os.system(&#39;mv %s %s&#39; %(filename, destination_directory))
    touch_Perf = os.path.join(Success_Directory_Perf, PerfSuccessFile )
           touch_file = open(touch_Perf,&quot;w&quot;)
    print touch_Perf
    touch_file.close()  
    os.system(&#39;rm %s&#39; % (rm_success))
           self.pool_sema.release()

def derectory_listing(directory):
 flist = os.listdir(directory)
 for i in range(len(flist)):
  full_path = os.path.join(Success_Directory,flist[i])
  statinfo = os.stat(full_path)
         flist[i] = statinfo.st_mtime,flist[i]
 flist.sort()
 x = []
 for i in range(len(flist)):
         x.append(flist[i][1])
 return x


#allfiles =  os.listdir(sys.argv[1])
allfiles = derectory_listing(sys.argv[1])
threadlist = []
for filter in filters:
    files = fnmatch.filter(allfiles, filter)
    if not files:
        continue
    thread = PROCESS(files, pool_sema, filter)
    threadlist.append(thread)
    thread.start()

for thread in threadlist:
    thread.join()

os.system(&#39;date&#39;)


#Usage: ./thread_merge_exception.py &quot;Directory Name&quot;
&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/8935476909302961110/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/network-wise-file-concatenation.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/8935476909302961110'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/8935476909302961110'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/network-wise-file-concatenation.html' title='Network Wise File Concatenation'/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-6781292070564964126</id><published>2012-10-17T18:00:00.000-07:00</published><updated>2012-10-17T18:00:02.740-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python Date Example"/><title type='text'>Python Script for Adding or Subtracting the Dates </title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Using Python Script we add and subtract the Dates in VMS platform   &lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
#----------------------------- 
# Adding to or Subtracting from a Date
# Use the rather nice datetime.timedelta objects

now = datetime.date(2003, 8, 6)
difference1 = datetime.timedelta(days=1)
difference2 = datetime.timedelta(weeks=-2)

print &quot;One day in the future is:&quot;, now + difference1
#=&gt; One day in the future is: 2003-08-07

print &quot;Two weeks in the past is:&quot;, now + difference2
#=&gt; Two weeks in the past is: 2003-07-23

print datetime.date(2003, 8, 6) - datetime.date(2000, 8, 6)
#=&gt; 1095 days, 0:00:00

#----------------------------- 
birthtime = datetime.datetime(1973, 01, 18, 3, 45, 50)   # 1973-01-18 03:45:50

interval = datetime.timedelta(seconds=5, minutes=17, hours=2, days=55) 
then = birthtime + interval

print &quot;Then is&quot;, then.ctime()
#=&gt; Then is Wed Mar 14 06:02:55 1973

print &quot;Then is&quot;, then.strftime(&quot;%A %B %d %I:%M:%S %p %Y&quot;)
#=&gt; Then is Wednesday March 14 06:02:55 AM 1973

#-----------------------------
when = datetime.datetime(1973, 1, 18) + datetime.timedelta(days=55) 
print &quot;Nat was 55 days old on:&quot;, when.strftime(&quot;%m/%d/%Y&quot;).lstrip(&quot;0&quot;)
#=&gt; Nat was 55 days old on: 3/14/1973

&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/6781292070564964126/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-script-for-adding-or-subtracting.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/6781292070564964126'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/6781292070564964126'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-script-for-adding-or-subtracting.html' title='Python Script for Adding or Subtracting the Dates '/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-5422641130291571989</id><published>2012-10-17T03:58:00.000-07:00</published><updated>2012-10-17T03:58:00.178-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python File Example"/><title type='text'>Program to create make file in VMS/UNIX</title><content type='html'>&lt;p&gt;This program will used to create a make file in either VMS or UNIX platform. We can use this as reusable module to import in some other program to generate make file in both platforms.  
  &lt;/p&gt;&lt;br/&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
#Program to create executable in either VMS or UNIX platform:
import osimport sys
def make(project_name, param = &quot;&quot;):    &quot;&quot;&quot;Builds a project with unit test directives on.        - project_name   the name of the project.    - param          (optional) but can be set to any parameter (taken by                     make.com) for VMS and only &quot;nodebug&quot; for UNIX.    &quot;&quot;&quot;        project_name = project_name.lower()        if  sys.platform == &quot;OpenVMS&quot;:        option = &#39;&#39;        if  param:            option = &#39; /&#39; + param        make_command = &#39;$ pre_c_defines = &quot;define=(&quot;&quot;UNITTEST&quot;&quot;)&quot;\n&#39; \                       &#39;$ pre_cxx_defines = &quot;define=(&quot;&quot;UNITTEST&quot;&quot;)&quot;\n&#39; \                       &#39;$ sym_comp_c_defines = &quot;/define=UNITTEST&quot;\n&#39; \                       &#39;$ sym_comp_cxx_defines = &#39; \                           &#39;&quot;/define=(UNITTEST,__USE_STD_IOSTREAM)&quot;\n&#39; \                       &#39;$ make &#39; + project_name + option + &#39;\n&#39;    else:  # UNIX platform        option = &#39;&#39;        if  param is &quot;nodebug&quot; and isdebug():            # This is the same as release command which is currently undefined.            option = &#39;unset sym_debug;. setdef.ksh &gt; /dev/null\n&#39;        make_command = option + \                       &#39;export sym_proc_parm=&quot;define=UNITTEST&quot;\n&#39; \                       &#39;export sym_comp_parm=&quot;-DUNITTEST&quot;\n&#39; \                       &#39;rmake &#39; + project_name    os.system(make_command)    return
&lt;/pre&gt;&lt;br/&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/5422641130291571989/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/program-to-create-make-file-in-vmsunix.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/5422641130291571989'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/5422641130291571989'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/program-to-create-make-file-in-vmsunix.html' title='Program to create make file in VMS/UNIX'/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-4146076454996559318</id><published>2012-10-16T14:30:00.000-07:00</published><updated>2012-10-16T14:30:00.572-07:00</updated><title type='text'>Python Code for creating Screen saver</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
This is the Python code for creating a screensaver of a moving ball. The ball will bee moving along the screen and when it hits any of the edges it will bounce back. If Python is installed in your mobile you can edit this code and create your own screen savers.  
 &lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
import appuifw
from graphics import *
import e32
from key_codes import *

class Keyboard(object):
    def __init__(self,onevent=lambda:None):
        self._keyboard_state={}
        self._downs={}
        self._onevent=onevent
    def handle_event(self,event):
        if event[&#39;type&#39;] == appuifw.EEventKeyDown:
            code=event[&#39;scancode&#39;]
            if not self.is_down(code):
                self._downs[code]=self._downs.get(code,0)+1
            self._keyboard_state[code]=1
        elif event[&#39;type&#39;] == appuifw.EEventKeyUp:
            self._keyboard_state[event[&#39;scancode&#39;]]=0
        self._onevent()
    def is_down(self,scancode):
        return self._keyboard_state.get(scancode,0)
    def pressed(self,scancode):
        if self._downs.get(scancode,0):
            self._downs[scancode]-=1
            return True
        return False
keyboard=Keyboard()


appuifw.app.screen=&#39;full&#39;
img=None
def handle_redraw(rect):
    if img:
        canvas.blit(img)
appuifw.app.body=canvas=appuifw.Canvas(
    event_callback=keyboard.handle_event,
    redraw_callback=handle_redraw)
img=Image.new(canvas.size)


running=1
def quit():
    global running
    running=0
appuifw.app.exit_key_handler=quit

location=[img.size[0]/2,img.size[1]/2]
speed=[0.,0.]
blobsize=16
xs,ys=img.size[0]-blobsize,img.size[1]-blobsize
gravity=0.03
acceleration=0.05



import time
start_time=time.clock()
n_frames=0

labeltext=u&#39;Use arrows to move ball&#39;
textrect=img.measure_text(labeltext, font=&#39;normal&#39;)[0]
text_img=Image.new((textrect[2]-textrect[0],textrect[3]-textrect[1]))
text_img.clear(0)
text_img.text((-textrect[0],-textrect[1]),labeltext,fill=0xffffff,font=&#39;normal&#39;)



while running:
    img.clear(0)
    img.blit(text_img, (0,0))
    img.point((location[0]+blobsize/2,location[1]+blobsize/2),
              0x00ff00,width=blobsize)
    handle_redraw(())
    e32.ao_yield()
    speed[0]*=0.999
    speed[1]*=0.999
    speed[1]+=gravity
    location[0]+=speed[0]
    location[1]+=speed[1]
    if location[0]&gt;xs:
        location[0]=xs-(location[0]-xs)
        speed[0]=-0.80*speed[0]
        speed[1]=0.90*speed[1]
    if location[0]&lt;0:
        location[0]=-location[0]
        speed[0]=-0.80*speed[0]
        speed[1]=0.90*speed[1]
    if location[1]&gt;ys:
        location[1]=ys-(location[1]-ys)
        speed[0]=0.90*speed[0]
        speed[1]=-0.80*speed[1]
    if location[1]&lt;0:
        location[1]=-location[1]
        speed[0]=0.90*speed[0]
        speed[1]=-0.80*speed[1]
        
    if keyboard.is_down(EScancodeLeftArrow):  speed[0] -= acceleration
    if keyboard.is_down(EScancodeRightArrow): speed[0] += acceleration
    if keyboard.is_down(EScancodeDownArrow):  speed[1] += acceleration
    if keyboard.is_down(EScancodeUpArrow):    speed[1] -= acceleration
    if keyboard.pressed(EScancodeHash):
        filename=u&#39;e:\\screenshot.png&#39;
        canvas.text((0,32),u&#39;Saving screenshot to:&#39;,fill=0xffff00)
        canvas.text((0,48),filename,fill=0xffff00)
        img.save(filename)

    n_frames+=1
end_time=time.clock()
total=end_time-start_time

print &quot;%d frames, %f seconds, %f FPS, %f ms/frame.&quot;%(n_frames,total,
                                                     n_frames/total,
                                                     total/n_frames*1000.)

&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/4146076454996559318/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-code-for-creating-screen-saver.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/4146076454996559318'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/4146076454996559318'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/python-code-for-creating-screen-saver.html' title='Python Code for creating Screen saver'/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-1021221321268582961</id><published>2012-10-16T03:49:00.000-07:00</published><updated>2012-10-16T03:49:00.898-07:00</updated><title type='text'>Run Application from host</title><content type='html'>&lt;br/&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
import os
os.execl( &quot;c:/Windows/Notepad.exe&quot;, &quot;c:/userlog.txt&quot;)
print &quot;Running notepad&quot;


#or

import subprocess
subprocess.call(&quot;c:/Windows/Notepad.exe&quot;)
print &quot;Running notepad&quot;



#starting a Web browser:

import os
os.system(&#39;/usr/bin/firefox&#39;)
os.system(r&#39;c:\&quot;Program Files&quot;\&quot;Mozilla Firefox&quot;\firefox.exe&#39;)


#Windows specific function os.startfile:

import os
os.startfile(r&#39; c:\Program Files\Mozilla Firefox\firefox.exe&#39;)

&lt;/pre&gt;&lt;br/&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/1021221321268582961/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/run-application-from-host.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/1021221321268582961'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/1021221321268582961'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/run-application-from-host.html' title='Run Application from host'/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-8036323528808535590</id><published>2012-10-15T14:30:00.000-07:00</published><updated>2012-10-15T14:30:00.414-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Multithreading"/><title type='text'>Multithreading in Python </title><content type='html'>&lt;p&gt; This code will give you clear view of how python programming is useful in threading compare to other programming language. 
&lt;/p&gt;&lt;br/&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
import threading,Queue,time,sys,traceback

#Globals (start with a captial letter)
Qin  = Queue.Queue() 
Qout = Queue.Queue()
Qerr = Queue.Queue()
Pool = []   

def err_msg():
    trace= sys.exc_info()[2]
    try:
        exc_value=str(sys.exc_value)
    except:
        exc_value=&#39;&#39;
    return str(traceback.format_tb(trace)),str(sys.exc_type),exc_value

def get_errors():
    try:
        while 1:
            yield Qerr.get_nowait()
    except Queue.Empty:
        pass

def process_queue():
    flag=&#39;ok&#39;
    while flag !=&#39;stop&#39;:
        try:
            flag,item=Qin.get() #will wait here!
            if flag==&#39;ok&#39;:
                newdata=&#39;new&#39;+item
                Qout.put(newdata)
        except:
            Qerr.put(err_msg())
            
def start_threads(amount=5):
    for i in range(amount):
         thread = threading.Thread(target=process_queue)
         thread.start()
         Pool.append(thread)
def put(data,flag=&#39;ok&#39;):
    Qin.put([flag,data]) 

def get(): return Qout.get() #will wait here!

def get_all():
    try:
        while 1:
            yield Qout.get_nowait()
    except Queue.Empty:
        pass
def stop_threads():
    for i in range(len(Pool)):
        Qin.put((&#39;stop&#39;,None))
    while Pool:
        time.sleep(1)
        for index,the_thread in enumerate(Pool):
            if the_thread.isAlive():
                continue
            else:
                del Pool[index]
            break
#STANDARD use:
for i in (&#39;b&#39;,&#39;c&#39;): put(i)
start_threads()
stop_threads()
for i in get_all(): print i
for i in get_errors(): print i

#POOL use
#put element into input queue
put(&#39;a&#39;)

#setup threads -- will run forever as a pool until you shutdown
start_threads() 

for i in (&#39;b&#39;,&#39;c&#39;): put(i)

#get an element from output queue
print get() 

#put even more data in, 7 causes an error
for i in (&#39;d&#39;,&#39;e&#39;,7): put(i)
#get whatever is available
for i in get_all(): print i

#stop_threads only returns when all threads have stopped
stop_threads()
print &#39;__threads finished last data available__&#39;
for i in get_all(): print i
for i in get_errors(): print i
#starting up threads again
start_threads()
put(&#39;f&#39;)
stop_threads()
print &#39;__threads finished(again) last data available__&#39;
for i in get_all(): print i
for i in get_errors(): print i

 
&lt;/pre&gt;&lt;br/&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/8036323528808535590/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/multithreading-in-python.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/8036323528808535590'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/8036323528808535590'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/multithreading-in-python.html' title='Multithreading in Python '/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6767613935004460333.post-3601412525441991559</id><published>2012-10-15T03:41:00.000-07:00</published><updated>2012-10-15T03:41:00.390-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Python File Example"/><title type='text'>This utility determines the size of a folder and its subfolders in MB </title><content type='html'>&lt;p&gt;This simple Python snippet will list the size of all the subfolders in a parent folder in MB.This is developed by using a python utility OS. &lt;/p&gt;&lt;br/&gt;
&lt;pre class=&quot;python&quot; name=&quot;code&quot;&gt;
# determine size of a given folder in MBytes

import os

# pick a folder you have ...
folder = &#39;D:\\zz1&#39;
folder_size = 0
for (path, dirs, files) in os.walk(folder):
  for file in files:
    filename = os.path.join(path, file)
    folder_size += os.path.getsize(filename)

print &quot;Folder = %0.1f MB&quot; % (folder_size/(1024*1024.0))
&lt;/pre&gt;&lt;br/&gt;
</content><link rel='replies' type='application/atom+xml' href='http://pythonprogramming.language-tutorial.com/feeds/3601412525441991559/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/this-utility-determines-size-of-folder.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/3601412525441991559'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6767613935004460333/posts/default/3601412525441991559'/><link rel='alternate' type='text/html' href='http://pythonprogramming.language-tutorial.com/2012/10/this-utility-determines-size-of-folder.html' title='This utility determines the size of a folder and its subfolders in MB '/><author><name>Raju Gupta</name><uri>http://www.blogger.com/profile/13350804494797609989</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>