Welcome, guest | Sign In | My Account | Store | Cart

Sometimes it is important to save data in the file but the file with the specified name already exists. This function creates a file name that is similar to the original by adding a unique numeric suffix. This avoids the renaming of existing files.

Python, 34 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
'''
function for making unique non-existent file name 
with saving source file extension
'''
import os
import sys

__author__ = 'Denis Barmenkov <denis.barmenkov@gmail.com>'
__source__ = 'http://code.activestate.com/recipes/577200-make-unique-file-name/'

def add_unique_postfix(fn):
    if not os.path.exists(fn):
        return fn

    path, name = os.path.split(fn)
    name, ext = os.path.splitext(name)

    make_fn = lambda i: os.path.join(path, '%s(%d)%s' % (name, i, ext))

    for i in xrange(2, sys.maxint):
        uni_fn = make_fn(i)
        if not os.path.exists(uni_fn):
            return uni_fn

    return None

def demo():
    script_path = sys.argv[0]
    print 'script file: %s' % script_path
    fn_unique = add_unique_postfix(script_path)
    print 'with unique postfix: %s' % fn_unique

if __name__ == '__main__':
    demo()
Created by Denis Barmenkov on Sun, 18 Apr 2010 (MIT)
Python recipes (4591)
Denis Barmenkov's recipes (20)

Required Modules

  • (none specified)

Other Information and Tasks