View Single Post
Old 12-10-2012, 04:43 PM   #9
ucpete
Member
 
Location: San Francisco Bay Area

Join Date: Dec 2008
Posts: 35
Default

Do you have any empty lines in the file? Otherwise, I don't know what to tell you-- it totally worked as is for me. Assuming you don't have some underlying problem with your input file, this will catch that error and proceed anyway:

Code:
inputFile = open("data.txt")
inputFile.next() # skip that first header line
frequencyDict = {}
for line in inputFile:
    try:
        curLength = int(line.strip().split(',')[2])
    except:
        continue
    if curLength in frequencyDict:
        frequencyDict[curLength] += 1
    else:
        frequencyDict[curLength] = 1
inputFile.close()

outputFile = open("data_transformed.txt",'w')
outputFile.write("Length, Quantity\n")
minLength, maxLength = min(frequencyDict.keys()), max(frequencyDict.keys())
for i in range(minLength,maxLength+1):
    if i in frequencyDict:
        outputFile.write("%s, %s\n" % (str(i),str(frequencyDict[i])))
outputFile.close()
ucpete is offline   Reply With Quote