移动文件,但如果python中存在,则重命名

2024-09-19 22:23:03 发布

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

我正在尝试在Windows中移动文件。当前文件位于驱动器C:下的文件夹中,但我想将它们移动到驱动器D:中的某个位置

我正在使用shutil.move函数,但如果文件存在,该函数将覆盖该文件。我希望在目标中保留文件的副本,而不是覆盖它。有这样的功能吗

def movefiles(strsrc, strdest, strextension):
    filelistsrc = []  #source files full path
    # store the destination of the current file
    dictfiles = {}

    for f in os.listdir(strsrc):
        if os.path.isfile(os.path.join(strsrc, f)):
            filefullname = os.path.join(strsrc, f)
            if filefullname.endswith(".html"):
                filelistsrc.append(filefullname)
                dictfiles[filefullname] = os.path.join(strdest, f)

    if not filelistsrc:
        return -1

    print("Start moving files from:")
    printstrlist(filelistsrc)

    for filename in filelistsrc:
        shutil.move(filename, dictfiles[filename])

    return 0

Tags: 文件path函数moveifosfilename驱动器
3条回答

在最后一个for循环中移动文件之前,您可以检查文件是否已经存在,并根据移动结果进行检查。我制作了一个递归函数,用于检查文件名并递增,直到文件名是新的:

import os

def renamefile(ffpath, idx = 1):
    
    #Rename the file from test.jpeg to test1.jpeg
    path, ext = os.path.splitext(ffpath)
    path, filename = path.split('/')[:-1], path.split('/')[-1]
    new_filename = filename + str(idx)
    path.append(new_filename + ext)
    path = ('/').join(path)

    #Check if the file exists. if not return the filename, if it exists increment the name with 1    
    if os.path.exists(path):
        print("Filename {} already exists".format(path))
        return renamefile(ffpath, idx = idx+1)
    
    return path

for filename in filelistsrc:
    if os.path.exists(filename):
        renamefile(filename)

    shutil.move(filename, dictfiles[filename])

如果文件已经存在,我们希望创建一个新文件,而不是覆盖它

for filname in filelistsrc:
    if os.path.exists(dictfiles[filename]):
        i, temp = 1, filename
        file_name, ext = filename.split("/")[-1].split(".")
        while os.path.exists(temp):
            temp = os.path.join(strdest, f"{file_name}_{i}.{ext}")
            dictfiles[filename] = temp
            i += 1
    shutil.move(filename, dictfiles[filename])

检查目的地是否存在。如果是,请创建新目标并移动文件

这是另一个解决方案

def move_files(str_src, str_dest):
    for f in os.listdir(str_src):
        if os.path.isfile(os.path.join(str_src, f)):
            # if not .html continue..
            if not f.endswith(".html"):
                continue

            # count file in the dest folder with same name..
            count = sum(1 for dst_f in os.listdir(str_dest) if dst_f == f)
            
            # prefix file count if duplicate file exists in dest folder
            if count:
                dst_file = f + "_" + str(count + 1)
            else:
                dst_file = f

            shutil.move(os.path.join(str_src, f),
                        os.path.join(str_dest, dst_file))

相关问题 更多 >