自动递增文件名Python - python

我试图编写一个函数,该函数将路径名和文件名分配给基于文件名(而不是文件夹中存在)的变量。然后,如果文件名已经存在,则文件名将自动递增。我已经看到了一些使用while循环的帖子,但是我对此一无所知,想将其包装在一个递归函数中。

这是我到目前为止所拥有的。使用打印语句进行测试时,每个方法都可以正常工作。但是它不会将新名称返回给主程序。

def checkfile(ii, new_name,old_name):

    if not os.path.exists(new_name):
        return new_name

    if os.path.exists(new_name):
        ii+=1
        new_name = os.path.join(os.path.split(old_name)[0],str(ii) + 'snap_'+ os.path.split(old_name)[1])
        print new_name

    old_name = “D:\Bar\foo”
    new_name= os.path.join(os.path.split(old_name)[0],”output_” + os.path.split(old_name)[1])
    checkfile(0,new_name,old_name)

python大神给出的解决方案

虽然我不建议为此使用递归(Python的堆栈在大约1000个函数调用处最大),但是您只是缺少递归位的返回:

new_name= os.path.join(os.path.split(old_name)[0],”output_” + os.path.split(old_name)[1])
checkfile(0,new_name,old_name)

相反,应为:

new_name= os.path.join(os.path.split(old_name)[0],”output_” + os.path.split(old_name)[1])
return checkfile(ii,new_name,old_name)

但是实际上,您可以通过将其重写为以下内容来简化整个过程:

 def checkfile(path):
     path      = os.path.expanduser(path)

     if not os.path.exists(path):
        return path

     root, ext = os.path.splitext(os.path.expanduser(path))
     dir       = os.path.dirname(root)
     fname     = os.path.basename(root)
     candidate = fname+ext
     index     = 0
     ls        = set(os.listdir(dir))
     while candidate in ls:
             candidate = "{}_{}{}".format(fname,index,ext)
             index    += 1
     return os.path.join(dir,candidate)

这种形式还可以处理文件名具有扩展名的事实,而您的原始代码没有扩展名,至少不是很清楚。它还避免了不必要的os.path.exist,这会非常昂贵,尤其是在路径是网络位置的情况下。