How to create new python file with increament number, if doesn't exist?

Denis McMahon denismfmcmahon at gmail.com
Mon May 27 06:49:00 EDT 2013


On Mon, 27 May 2013 02:27:59 -0700, Avnesh Shakya wrote:

> I want to create a new python file like 'data0.0.5', but if it is
> already exist then it should create 'data0.0.6', if it's also exist
> then next like 'data0.0.7'. I have done, but with range, please give
> me suggestion so that I can do it with specifying range.

Try and put your description into the sequence of instructions you want 
the computer follow.

For this problem, my sequence of instructions would be:

1) Find the highest numbered existing file that matches the filename 
data0.0.[number]

2) Create a new file that is one number higher.

Now the solution is easy. Find the list of filenames in the directory 
that match a suitable regular expression, take the numeric value of a 
substring of the filename for each file and find the highest, add one to 
it, then create the new file name.

Something like the following (untested) with the relevant imports etc:

nfn="data0.0."+str(max([int(f[8:])for f in os.listdir(p)if re.match
('^data0.0.[0-9]+$',f)])+1)

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list