Example of Python.

Oh, how great Python is. It always amazes me how much one can do with such scripting tool. I just wrote a simple program for a friend that searches the input text file for a given a pattern an writes that twice to the output it finds it, if not, just once.

I’m posting it here for people to see how easy it is to get input args and string comparison and even simple exception handilng:

#¬†¬† ¬†Duplicates some certain lines in the input file starting with “DFFR_X1”

import sys

#opening file

whatToDetect = sys.argv[1]
inputFileArg = sys.argv[2]
outputFileArg = sys.argv[3]

inputFileObj = open(inputFileArg, ‘r’)
ouputFileObj = open(outputFileArg, ‘w’)

numOfDuplicates = 0

if len(whatToDetect) == 0:
print(“No pattern to match was given.”)

print(“Lenght of input is “,len(whatToDetect))

try:
for line in inputFileObj:
if line[0:len(whatToDetect)] == whatToDetect:
ouputFileObj.write(line)
numOfDuplicates = numOfDuplicates + 1
ouputFileObj.write(line)
except IOError as exc:
raise CustomError(‘something went wrong’) from exc

inputFileObj.close()
ouputFileObj.close()

print (“Number of duplicates was “,numOfDuplicates)

Leave a Reply

Your email address will not be published. Required fields are marked *