我有一个包含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复制到其中。顺便说一句,如果你用“复制”更好,因为当你用“移动”的时候,如果你做错了什么,你基本上把所有的东西都混在一起了。
相关问题 更多 >
编程相关推荐