Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #46186

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

From Denis McMahon <denismfmcmahon@gmail.com>
Newsgroups comp.lang.python
Subject Re: How to create new python file with increament number, if doesn't exist?
Date 2013-05-27 10:49 +0000
Organization A noiseless patient Spider
Message-ID <knvdms$gvn$3@dont-email.me> (permalink)
References <3c99daa0-6f30-4cbf-b107-56021a324f7c@googlegroups.com>

Show all headers | View raw


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@gmail.com

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

How to create new python file with increament number, if doesn't exist? Avnesh Shakya <avnesh.nitk@gmail.com> - 2013-05-27 02:27 -0700
  Re: How to create new python file with increament number, if doesn't exist? Denis McMahon <denismfmcmahon@gmail.com> - 2013-05-27 10:49 +0000
    Re: How to create new python file with increament number, if doesn't exist? Avnesh Shakya <avnesh.nitk@gmail.com> - 2013-05-27 16:30 +0530
  Re: How to create new python file with increament number, if doesn't exist? jt@toerring.de (Jens Thoms Toerring) - 2013-05-27 11:13 +0000

csiph-web