More Pythoning!

So, as my friend requested, I change the program to meet his more advance requirements. See if you can understand what this program does!

#    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]

#whatToDetect = ”  Z”
#inputFileArg = “input.txt”
#outputFileArg = “output.txt”

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)

arrayOfLinesToBeCopied = []
#arrayOfLinesToBeCopied.append(1)
#print arrayOfLinesToBeCopied[0]

try :
#inputFileObj.open
for currentLine in inputFileObj:
print currentLine + ” for”
if currentLine[0 : len(whatToDetect)] == whatToDetect:
arrayOfLinesToBeCopied.append( currentLine )
while not “;” in currentLine :
print currentLine + ” while”
print “appending”
currentLine = inputFileObj.next()
arrayOfLinesToBeCopied.append( currentLine )
else :
arrayOfLinesToBeCopied.append( currentLine )
print “ELSE SEKTION”
for i in range (2) :
print range(0, len(arrayOfLinesToBeCopied))
for i in range(0, len(arrayOfLinesToBeCopied) – 1) :
print i
ouputFileObj.write(arrayOfLinesToBeCopied[i])
#print arrayOfLinesToBeCopied[i]

arrayOfLinesToBeCopied = []
#print “-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-”
else:
ouputFileObj.write(currentLine)
except (IOError), exc :
raise CustomError(‘something went wrong’)

inputFileObj.close()
ouputFileObj.close()

print “Number of duplicates was “,numOfDuplicates

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)