[Tutor] Creating new files w/o overwriting existing ones

Dick Moores rdm at rcblue.com
Mon Apr 9 15:47:22 CEST 2007


At 03:39 AM 4/9/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>Sorry if my Subject line isn't clear about what my question is.
>>I have a script that uses the turtle and random modules to create 
>>SVG files, one after another, in a directory just for the SVGs. The 
>>script assigns filenames in the form, "n.svg", where n is an 
>>integer. E.g. 1.svg, 2.svg. 3.svg, ... 44.svg, 45.svg. As it is 
>>now, I have to reset the starting integer when restarting the 
>>script, so as to not overwrite the files already created. Thus if 
>>the highest number filename is 45.svg, I have to configure the 
>>script so that it begins to create SVGs with filenames of 46.svg on up.
>>I'm hoping to add a function that will find find that highest 
>>number filename in the directory. Is this possible?
>>I should add that the numbers of the existing files will not 
>>necessarily be consecutive. There could be gaps. E.g., 4.svg.,
>
>Just look at the existing files and figure out the max. This is 
>pretty straightforward with os.listdir(), simple string 
>manipulations - endswith() and split() or os.path.splitext() - and 
>the int() function to convert the prefix to an integer.
>
>I wasn't going to show you the code but I can't resist putting it 
>into a one-liner (which will break if you have other files in the same dir) -
>max(int(os.path.splitext(f)[0]) for f in os.listdir(...) if 
>f.endswith('.svg'))
>
>Setting a bad example for tutors everywhere :-)

Thanks, Kent. All I really needed to know was that there was an 
os.listdir(). I thought I'd try writing the function without looking 
at how you got the max, and here's what I came up with:

def nextSVGnum():
     lstSvg = listdir("E:\Python25\dev\Turtle\SVG")
     lstNums = []
     for x in lstSvg:
         num = int(x.split('.')[0])
         lstNums.append(num)
     nextSVGnum = max(lstNums) + 1
     return nextSVGnum

This fits with the function that creates the SVG:
def createSVG(nextSVGnum):
     fldrPth = "E:\Python25\dev\Turtle\SVG\\"
     svgName = str(nextSVGnum) + ".svg"
     SVG_path = fldrPth + svgName
     canvasvg.saveall(SVG_path, T._canvas)
     return nextSVGnum + 1

BTW for anyone interested, I got the canvasvg module from 
<http://wmula.republika.pl/proj/canvas2svg/>.

Dick 



More information about the Tutor mailing list