已解决
python应用(9)——将一个文件夹里的图片分配到多个文件夹内
来自网友在路上 171871提问 提问时间:2023-10-22 04:32:01阅读次数: 71
最佳答案 问答题库718位专家为你答疑解惑
需求:将一个文件夹里的所有图片分到多个文件夹中,假设要求每个文件夹里分到100张图片,当分到最后不足100张图时,也正常进行
代码如下(示例):
import os
import shutildef split_images(source_folder, destination_folder, images_per_folder):# 确保目标文件夹存在os.makedirs(destination_folder, exist_ok=True)# 获取源文件夹中的所有图片文件image_files = [f for f in os.listdir(source_folder) if os.path.isfile(os.path.join(source_folder, f))]# 计算需要创建的目标文件夹数量num_folders = len(image_files) // images_per_folderif len(image_files) % images_per_folder > 0:num_folders += 1# 将图片分配到目标文件夹中for i in range(num_folders):folder_name = f"folder_{i+1}"folder_path = os.path.join(destination_folder, folder_name)os.makedirs(folder_path, exist_ok=True)# 计算当前目标文件夹应包含的图片范围start_index = i * images_per_folderend_index = (i + 1) * images_per_folder# 处理最后一个文件夹,如果图像数量不足images_per_folderif i == num_folders - 1 and len(image_files) % images_per_folder > 0:end_index = len(image_files)# 将图片复制到目标文件夹for j in range(start_index, end_index):image_file = image_files[j]source_file_path = os.path.join(source_folder, image_file)destination_file_path = os.path.join(folder_path, image_file)shutil.copyfile(source_file_path, destination_file_path)print(f"Created folder {folder_name} and copied {end_index - start_index} images.")# 示例用法
source_folder = "C:/Users/jutze/Desktop/353S02073"
destination_folder = "C:/Users/jutze/Desktop/IC_contours"
images_per_folder = 100split_images(source_folder, destination_folder, images_per_folder)
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"python应用(9)——将一个文件夹里的图片分配到多个文件夹内":http://eshow365.cn/6-21311-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!