Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shutil.move if directory already exists

Tags:

python

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)
like image 695
Tom Cider Avatar asked Jul 16 '17 23:07

Tom Cider


1 Answers

Use copy insted of move, it should overwrite files automatically

shutil.copy(sourcePath, destinationPath)

Then of course you need to delete original files. Be aware, shutil.copy does not copy or create directories, so you need to make sure they exist.

If this does not work either, you can manually check if file exists, remove it, and move new file:

To check that file exists, use:

from pathlib import Path my_file = Path("/path/to/file")

if my_file.exists(): to check that something at path exist

if my_file.is_dir(): to check if directory exists

if my_file.is_file(): to check if file exists

To delete directory with all its contents use: shutil.rmtree(path)

Or delete a single file with os.remove(path) and then move them one by one

like image 197
Justas G Avatar answered Oct 16 '22 06:10

Justas G