Python copy files to a new directory and rename if file name already exists

后端 未结 4 636
梦毁少年i
梦毁少年i 2021-02-02 06:24

I\'ve already read this thread but when I implement it into my code it only works for a few iterations.

I\'m using python to iterate through a directory (lets call it m

4条回答
  •  感情败类
    2021-02-02 07:20

    Sometimes it is just easier to start over... I apologize if there is any typo, I haven't had the time to test it thoroughly.

    movdir = r"C:\Scans"
    basedir = r"C:\Links"
    # Walk through all files in the directory that contains the files to copy
    for root, dirs, files in os.walk(movdir):
        for filename in files:
            # I use absolute path, case you want to move several dirs.
            old_name = os.path.join( os.path.abspath(root), filename )
    
            # Separate base from extension
            base, extension = os.path.splitext(filename)
    
            # Initial new name
            new_name = os.path.join(basedir, base, filename)
    
            # If folder basedir/base does not exist... You don't want to create it?
            if not os.path.exists(os.path.join(basedir, base)):
                print os.path.join(basedir,base), "not found" 
                continue    # Next filename
            elif not os.path.exists(new_name):  # folder exists, file does not
                shutil.copy(old_name, new_name)
            else:  # folder exists, file exists as well
                ii = 1
                while True:
                    new_name = os.path.join(basedir,base, base + "_" + str(ii) + extension)
                    if not os.path.exists(new_name):
                       shutil.copy(old_name, new_name)
                       print "Copied", old_name, "as", new_name
                       break 
                    ii += 1
    

提交回复
热议问题