shutil.move if directory already exists

Viewed 25418

I have a code that I am using to move all jpg files from source to destination. First time the code runs fine and it moves the files but if I run it again, it gives an error that the file already exists.

Traceback (most recent call last):
  File "/Users/tom/Downloads/direc.py", line 16, in <module>
    shutil.move(jpg, dst_pics)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/shutil.py", line 542, in move
    raise Error("Destination path '%s' already exists" % real_dst)
shutil.Error: Destination path '/Users/tom/Downloads/Dest/Pictures/Photo3.jpg' already exists

Here is my code

import os
import glob
import shutil

local_src = '/Users/tom/Downloads/'
destination = 'Dest'

src = local_src + destination
dst_pics = src + '/Pictures/'

print(dst_pics)

for pic in glob.iglob(os.path.join(src, "*.jpg")):
    if os.path.isfile(pic):
        if not (os.path.isfile(dst_pics + pic)):
            shutil.move(pic, dst_pics)
        else:
            print("File exists")

Is there anything that I can do so it can overwrite the file or checks to see if the file exists and skip it?

I was able to solve it by following @Justas G solution.

Here is the solution

for pic in glob.iglob(os.path.join(src, "*.jpg")):
    if os.path.isfile(pic):
        shutil.copy2(pic, dst_pics)
        os.remove(pic)
2 Answers

In addition to the code above I move folder into already existing directories and this collision will produce an error so I recommend shutil.copytree()

shutil.copytree('path_to/start/folder', 'path_to/destination/folder', dirs_exist_ok=True) 

The dirs_exist_ok=True is required to allow overwriting files, otherwise you will get an error.

Related