如何找到双重文件夹下的所有图片并保存在一起 python代码实现
时间: 2023-12-29 07:03:02 浏览: 22
可以使用Python的os、os.path和shutil库来实现。以下是一个示例代码:
```python
import os
import shutil
# 定义函数,遍历文件夹并保存所有图片
def save_all_images(root_folder):
image_folder = os.path.join(root_folder, 'images')
if not os.path.exists(image_folder):
os.makedirs(image_folder)
for foldername, subfolders, filenames in os.walk(root_folder):
for filename in filenames:
if filename.endswith('.jpg') or filename.endswith('.png'):
filepath = os.path.join(foldername, filename)
shutil.copy2(filepath, image_folder)
# 调用函数,传入双重文件夹路径
root_folder = r'C:\Users\username\Documents\double_folder'
save_all_images(root_folder)
```
在上面的代码中,我们使用了os.walk()函数来遍历双重文件夹,如果文件夹中有images文件夹则将图片保存在该文件夹下,如果没有则创建images文件夹并保存图片。使用shutil.copy2()函数来复制图片文件到目标文件夹中。