【发布时间】:2023-06-20 05:21:01
【问题描述】:
我有一个包含 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)))
【问题讨论】:
-
....errr..... 是吗?
-
@Mark Setchell - 详细说明??
-
Linux/macOS 上有更强大的工具,不需要你为此编写代码,仅此而已。
标签: python python-3.x image python-imaging-library batch-processing