Zen*_*883 4 python image batch-processing python-imaging-library python-3.x
我有一个包含 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)))
Run Code Online (Sandbox Code Playgroud)
您可以尝试使用 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11223 次 |
| 最近记录: |