python函数不重复

问题描述

| 我有一个python工具来\'touch \'(utime)一个文件,然后移到另一个文件夹。但是,如果该文件已存在于目标文件夹中,它将被静覆盖。我想在目标文件夹中检查一个同名文件,如果存在,则将我要移动的文件重命名文件名,最后加上\'-n \',其中n是一个以\开头的数字。 '1 \',如果末尾带有\'-1 \'的文件已经存在,则\'-2 \'等。 例如,假设源文件夹中有一个\'foo.txt \'文件,但目标文件夹中也有一个\'foo.txt \'。此函数应返回\'(绝对路径)/foo-1.txt \'。 因此,我已经创建了一个函数来检查这些情况并返回修改后的字符串,以便以后可以使用重命名而不覆盖。但是,当前,如果文件存在,则不返回任何内容。以下是函数代码,假设使用这些变量: fileName-输入文件路径,绝对路径。例如/Users/foo/sourceFolder/bar.txt index-迭代器变量,在打开每个文件的开始时设置为\'1 \'(外部作用)
def checkExists(fileName):
    global index
    print \"checkExists(\" + fileName + \")\"

    if exists(fileName):
        splitPath = split(newFile)
        splitName = splitext(splitPath[1])
        newSplitName = splitName[0] + \"-\" + str(index)

        index += 1
        newName = splitPath[0] + \"/\" + newSplitName + splitName[1]

        print \"newName = \" + newName
    else:
        print \"(else) fileName = \" + fileName
        print \"(else) fileName = \" + str(type(fileName))
        print \"\"
        return fileName

    checkExists(newName)
现在,似乎对内部的checkExists()的调用未在运行。 我希望我的解释很清楚。 皮卡 附言我不想听到有关utime潜在种族问题的信息,我知道源目录中的文件将不会被其他任何文件访问。     

解决方法

您的问题是,如果文件存在,则不返回任何内容。我认为您打算使用递归检查新文件名,但是您不返回该调用的结果。这里是一个刺:
def checkExists(fileName,index=0):
    print \"checkExists(\" + fileName + \")\"

    if exists(fileName):
        splitPath = split(newFile)
        splitName = splitext(splitPath[1])
        newSplitName = splitName[0] + \"-\" + str(index)

        index += 1
        newName = splitPath[0] + \"/\" + newSplitName + splitName[1]

        print \"newName = \" + newName
        return checkExists(newName,index)   # recurse
    else:
        print \"(else) fileName = \" + fileName
        print \"(else) fileName = \" + str(type(fileName))
        print \"\"
        return fileName
我还自由地将递归调用移到了
newName
的生成位置,并删除了全局变量并将其替换为递归。     ,这是解决类似问题的一种迭代方法:
def copyfile(path,dstdir,verbose=True,dryrun=False):
    \"\"\"Copy `path` file to `dstdir` directory incrementing name if necessary.\"\"\"
    filename = os.path.basename(path)
    basename,ext = os.path.splitext(filename)

    for i in itertools.count(2):
        destpath = os.path.join(dstdir,filename)
        if not os.path.exists(destpath):
            if verbose:
                print(path,\'->\',destpath)
            if not dryrun:
                shutil.copyfile(path,destpath)
            return
        # increment filename
        filename = \"%s_%02d%s\" % (basename,i,ext)