Python - 按文件名将文件移动到文件夹

2024-09-29 23:22:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含10个图像的文件夹,我希望根据当前文件名将其移动到新文件夹中。我已经成功地将文件夹中的每个图像移到了一个新文件夹中,而且从现在起,我已经成功地将每个图像文件名移到了自己的文件夹中,但是我还没有弄清楚如何将具有相同文件名的所有图像移到一个文件夹中,并将另一个移到另一个文件夹中。例如下面我要相应地移动图像。

  • 1600_01.jpg--->;文件夹1
  • 1700_01.jpg--->;文件夹1
  • 1800_02.jpg--->;文件夹2
  • 1900_02.jpg--->;文件夹2
  • 2000_03.jpg--->;文件夹3
  • 2100_03.jpg--->;文件夹3

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

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)))

这是我运行脚本后得到的。 This is what I got after I ran my script

但是,下面的图片显示了我要做的事情: Goal


Tags: thepath图像gt文件夹newos文件名
0条回答
网友
1楼 · 发布于 2024-09-29 23:22:12

您可以尝试使用os.path.exists()检查文件夹是否存在,如果存在,请将jpg复制到其中。顺便说一句,如果你用“复制”更好,因为当你用“移动”的时候,如果你做错了什么,你基本上把所有的东西都混在一起了。

import os, shutil

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

for f in os.listdir("folder"):
    folderName = f[-6:-4]

    if not os.path.exists(folderName):
        os.mkdir(folderName)
        shutil.copy(os.path.join('folder', f), folderName)
    else:
        shutil.copy(os.path.join('folder', f), folderName)

enter image description here

相关问题 更多 >

    热门问题