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

Kent Johnson kent37 at tds.net
Mon Apr 9 12:39:46 CEST 2007

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 

Setting a bad example for tutors everywhere :-)

More information about the Tutor mailing list