Python: 根据文件名将文件移动到文件夹

Python: Moving files to folder based on filenames

我有一个包含 10 张图像的文件夹,我希望根据它的当前文件名将它们移动到一个新文件夹中。我已经成功地将文件夹中的每个图像移动到一个新文件夹中,到目前为止,我已经成功地将每个图像文件名移动到它自己的文件夹中,但我还没有弄清楚如何移动所有图像相同的文件名到一个文件夹,另一个到另一个文件夹。例如下面我想相应地移动图像。

到目前为止,这是我通过基于图像文件名创建新文件夹将图像文件移动到新文件夹的代码。我得到了制作文件夹的部分,但是当它为所有图像创建单独的图像文件夹时我很困惑。

import os, shutil, glob

#Source file 
sourcefile = 'Desktop/00/'

# for loop then I split the names of the image then making new folder 
for file_path in glob.glob(os.path.join(sourcefile, '*.jpg*')):
    new_dir = file_path.rsplit('.', 1)[0]    
    # If folder does not exist try making new one
    try:
        os.mkdir(os.path.join(sourcefile, new_dir))
    # except error then pass
    except WindowsError:
        pass
    # Move the images from file to new folder based on image name
    shutil.move(file_path, os.path.join(new_dir, os.path.basename(file_path)))

这是我 运行 我的脚本后得到的。

但是,我正在尝试做的事情如下图所示:

您可以使用os.path.exists()检查该文件夹是否存在,如果存在则将jpg复制到其中。

旁注:最好使用copy。当你使用 move 时,如果你做错了什么,你可以把所有东西都弄混。

import os
import shutil

os.chdir("<abs path to desktop>")

for f in os.listdir("folder"):
    folder_name = f[-6:-4]
    
    if not os.path.exists(folder_name):
        os.mkdir(folder_name)
        shutil.copy(os.path.join("folder", f), folder_name)
    else:
        shutil.copy(os.path.join("folder", f), folder_name)