Moving a folder to itself: shutil, check if file's path is the same as the destination path, if so do nothing

Viewed 48

I have the following code which works as expected, expect when the source file is the same as the destination file. I have tried os.path. isfile/isdir/exists but I'm hitting a wall.

So essentially this loops through the file_list and moves the file in the list to the destination. However, it can happen that the source and destination are the same, so, if the file's location is the same as the destination, then it is trying to move itself to itself and obviously fails. So in the following I need to add a check, if the file's location (source) is the same as the destination then pass.

    def move_files(file_list, destination):
        for file in file_list:
            source_file = file
            shutil.move(source_file, destination)

In this case the destination is a folder path and the source is a folder path + file name, so I need to ignore the source's file name and compare the path with the destination.

I feel I'm over complicating this, but any help is appreciated.

2 Answers

You can make use of abspath and dirname methods of os.path. The first one returns the absolute path of a directory, the second provides the directory name of a path.

def move_files(file_list, destination):
    # just in case you don't provide absolute paths
    # you can also consider using `expanduser`
    destination = os.path.abspath(destination)
    for file in file_list:            
        file_abs_path = os.path.abspath(file)
        if os.path.dirname(file_abs_path) != destination: 
            shutil.move(file_abs_path, destination)

https://docs.python.org/3/library/os.path.html#os.path.abspath

https://docs.python.org/3/library/os.path.html#os.path.dirname

https://docs.python.org/3/library/os.path.html#os.path.expanduser

I think this is what you want

And also, i've found the source_file variable des nothing special here. So i just ignored it.

import os
import shutil

def move_files(file_list, destination):
    dir_lst = os.listdir(destination)
    for file in file_list:
        if file not in dir_lst: # This will only move the files if its not in the destination folder
            shutil.move(file, destination)

For a complete code using only os module,

import os

def move_files(file_list, destination):
    dir_lst = os.listdir(destination)
    for file in file_list:
        if file not in dir_lst: # This will only move the files if its not in the destination folder
            os.rename(file, destination)
Related