自动递增文件名Python

2024-04-24 22:57:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个函数,它将路径名和文件名分配给一个基于文件夹中存在的文件名的变量。然后,如果文件名已经存在,则文件名将自动递增。我已经看到一些关于这个使用while循环的帖子,但是我无法理解这一点,我想用递归函数来包装它。在

这是我到目前为止的情况。当使用print语句进行测试时,每种方法都很好。但它不会将新名称返回主程序。在

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)

Tags: path函数namenewifos文件名exists
1条回答
网友
1楼 · 发布于 2024-04-24 22:57:18

虽然我不建议对此使用递归(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)

应改为:

^{pr2}$

但实际上,你可以把它改写成:

 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,这可能是非常昂贵的,特别是如果路径是一个网络位置。在

相关问题 更多 >