Text processing and file creation

Shawn Milochik Shawn at Milochik.com
Thu Sep 6 18:39:31 CEST 2007


Here's my solution, for what it's worth:

#!/usr/bin/env python

import os

input = open("test.txt", "r")

counter = 0
fileNum = 0
fileName = ""

def newFileName():

    global fileNum, fileName


    while os.path.exists(fileName) or fileName == "":
        fileNum += 1
        x = "%0.5d" % fileNum
        fileName = "%s.tmp" % x

    return fileName


for line in input:

    if (fileName == "") or (counter == 5):
        if fileName:
            output.close()
        fileName = newFileName()
        counter = 0
        output = open(fileName, "w")

    output.write(line)
    counter += 1

output.close()



More information about the Python-list mailing list