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

Jens Thoms Toerring jt at toerring.de
Mon May 27 07:13:19 EDT 2013


Avnesh Shakya <avnesh.nitk at gmail.com> 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.
> I was trying this way and it's working also..

>     i = 0
>     for i in range(100):
>         try:
>             with open('Data%d.%d.%d.json'%(0,0,i,)): pass
>             continue
>         except IOError:
>             edxCorrectDataFile = file('Data%d.%d.%d.json'%(0,0,i,), 'a+')
>             break

> But here I have defined range 100, Is it possible without range it create
> many required files?

What about something as simple as this?

  i = 0
  while os.path.exists( 'Data{0}.{1}.{2}.json'.format( 0, 0, i ) ) :
      i += 1
  f = open( 'Data{0}.{1}.{2}.json'.format( 0, 0, i ), 'w' )

For your code you'ld make it e.g.

  i = 0
  try:
      while True :
          with open('Data%d.%d.%d.json'%(0,0,i)):
              i += 1
  except IOError:
      edxCorrectDataFile = file('Data%d.%d.%d.json'%(0,0,i), 'a+')

Note that I don't see how all this trying to open a file and
catching an exeception if it doesn't exist is any better
than simply using os.path.exists(). You may have read some-
where that it avoids a race condition and would thus be more
secure. That's not the case here, an attacker still could
create e.g. a symbolic link with the name of the file you're
going to open between the time the exception is thrown and your
program getting around to open the file you expect not to exist,
so nothing is gained by using this somewhat convoluted method.
What would be needed for avoiding a race condition is an addi-
tional flag to be passed to open() like the for example the
O_EXCL flag that can be passed to Unix' open() system function.
But that isn't supported by Pythons open() function which
rather likeky is based on C's fopen() function). The best
advice to avoid such problems is probably not to open files
with a predictable name (or better to use one of the methods
to create files with names guaranteed to be unique by the
system) in directories to which other users than you also
have write permission.
                            Regards, Jens
-- 
  \   Jens Thoms Toerring  ___      jt at toerring.de
   \__________________________      http://toerring.de



More information about the Python-list mailing list