Moving files into specific directory using python get error file already exist

When I run my code I get the same error like this :

---------------------------------------------------------------------------
Error                                     Traceback (most recent call last)
<ipython-input-54-8d584fc326c3> in <module>
     16         filesToMove = gen_find("B"+str(o)+"_*",src)
     17         for name in filesToMove:
---> 18             shutil.move(name, dst)
Error: Destination path 'Dataset/300_train/1\B1_1.jpg' already exists

Can anyone help me to check my code here?:

please give some explaination

import os
import shutil
import fnmatch

def gen_find(filepat,top):
    for path, dirlist, filelist in os.walk(top):
        for name in fnmatch.filter(filelist,filepat):
            yield os.path.join(path,name)

ranges = list(range(1,51))
for o in ranges:
    if __name__ == '__main__':
        src = 'Dataset/300_train' # input
        dst = 'Dataset/300_train/'+str(o) # desired     location

        filesToMove = gen_find("B"+str(o)+"_*",src)
        for name in filesToMove:
            shutil.move(name, dst)

I want to skip to copy the file if there's already exists

Upvotes: 1

Views: 85

Answers (1)

Ofer Sadan
Ofer Sadan

Reputation: 11922

As you meantioned in your comment, if you want to skip the file if it's already there, it's really quite simple with a try... except block. You need to replace this part of your code

for name in filesToMove:
    shutil.move(name, dst)

with this:

for name in filesToMove:
    try:
        shutil.move(name, dst)
    except shutil.Error:
        pass

Upvotes: 2

Related Questions