将文件夹移动到自身:shutil,检查文件路径是否与目标路径相同,如果是则什么都不做

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

我有以下代码可以按预期工作,期望源文件与目标文件相同。我试过 os.path. isfile/isdir/exists 但我碰壁了。

所以本质上这是循环遍历 file_list 并将列表中的文件移动到目的地。但是,源和目标可能相同,因此,如果文件的位置与目标相同,那么它会尝试将自身移动到自身,但显然会失败。所以在下面我需要添加一个检查,如果文件的位置(源)与目标相同,那么 pass.

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

在这种情况下,目标是文件夹路径,源是文件夹路径+文件名,所以我需要忽略源的文件名并将路径与目标进行比较。

我觉得我把这件事复杂化了,但我们感谢您的帮助。

我想这就是你想要的

另外,我发现 source_file 变量 des 在这里没什么特别的。所以我直接无视了。

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)

对于仅使用 os 模块的完整代码,

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)

您可以使用 os.pathabspathdirname 方法。第一个returns一个目录的绝对路径,第二个提供一个路径的目录名。

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