My love for Python has indeed grown with the constant usage. Each day i find something that is really interesting with that. By interesting i mean, C will complain and whine if i do that, PERL say ‘lets give it a try‘ and Python is like, ‘C’mon baby, i’m ready!!!’.
My advice to good C/C++ programmers is that, stay the way you are, picking up PERL / Python will screw up you skill. C is like the wife with whom you have to be loyal, Python is like the liberal girlfriend, who lets you flirt with other girls and wouldn’t mind.
Coming back to the purpose of this post, here are some of the snippets that proved useful to me and could also help you out with in your scripts -
File to List – Move the contents of the file in to an list, line by line
list = ([line for line in open ( "names.txt", "r")])
Pattern Matching – the only thing that i miss in Python is the regexp usability that PERL gave me. Some how i feel that using regexp was a lot more easier with Perl, than with Python
# import the regex pacakge
import re
#create the regex object
pattern = re.compile("error")
# search for pattern
re.search(pattern, sampleString)
re.search return TRUE / FALSE depending on the result, so that it can be used along with if <> : clause
Detecting the OS and creating directories – this helps to solve the variation in the Windows directory navigation (..\\..\\) and the Unix style navigation (../../)
# import OS packages and time package
import os, time, sys, os.path
# create a unique directory name based on the time
dirName="Run-"+time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
# detect the OS
if os.name == "posix":
logPath = "../../logs/"
resultsPath = "../../results/"
else:
logPath = "..\\..\logs\\"
resultsPath = "..\\..\\results\\"
# create the directories
os.mkdir(logPath+dirName)
os.mkdir(resultsPath+dirName)
String is like a List – the best part of Python
str = "Hello"
# will print H
print str[0]
Happy scripting, and i hope this will be helpful to some …


