我现在有两个文件夹,一个文件夹里面有很多张图片,另一个文件夹里面又有一个子文件夹,这个子文件夹里面也有很多张图片,请给出python代码对两个文件夹里面图片的数量进行比较,如果数量不同请告诉我具体是哪张图片的数量不同
时间: 2024-04-16 16:23:53 浏览: 134
以下是一个用Python编写的代码示例,用于比较两个文件夹中图片的数量,并告诉您具体哪张图片的数量不同:
```python
import os
def count_images(folder_path):
count = 0
for file in os.listdir(folder_path):
if file.endswith(".jpg") or file.endswith(".png"):
count += 1
return count
def compare_image_counts(folder1, folder2):
images1 = {file: 0 for file in os.listdir(folder1)}
images2 = {file: 0 for file in os.listdir(folder2)}
for file in images1:
if file.endswith(".jpg") or file.endswith(".png"):
images1[file] = count_images(os.path.join(folder1, file))
for file in images2:
if file.endswith(".jpg") or file.endswith(".png"):
images2[file] = count_images(os.path.join(folder2, file))
different_images = []
for file in images1:
if images1[file] != images2.get(file, 0):
different_images.append(file)
return different_images
folder1_path = "path/to/folder1"
folder2_path = "path/to/folder2"
different_images = compare_image_counts(folder1_path, folder2_path)
if len(different_images) > 0:
print("The following images have different counts:")
for image in different_images:
print(image)
else:
print("The image counts in the two folders are the same.")
```
请将`"path/to/folder1"`和`"path/to/folder2"`替换为您实际的文件夹路径。代码将比较两个文件夹中所有以`.jpg`或`.png`结尾的图片的数量,并输出具有不同数量的图片的文件名。如果两个文件夹中的图片数量相同,则输出相应的消息。
阅读全文