python - 我如何查看文件夹中有多少个 png 文件及其分辨率以打印到 excel 中?
问题描述
我的文件夹结构如下
- 数据集文件夹
- 子文件夹 1
- a.png b.png c.png...
- 子文件夹 2
- a.png b.png c.png...
- 子文件夹 3
- a.png b.png c.png...
- 子文件夹4
- a.png b.png c.png...
- 子文件夹 n
- a.png b.png c.png...
- 子文件夹 1
解决方案
您可以使用 递归查找文件glob.glob()
,但我使用os.walk()
和str.endswith(".png")
收集所有子目录中的所有 png 文件。
出色的Pillow模块用于获取图像的分辨率。
import os
from collections import defaultdict
from PIL import Image
DIR = r"C:\Dataset Folder"
results = defaultdict(list)
for root, _, filenames in os.walk(DIR):
subdirectory = root.replace(f"{DIR}\\", "")
for filename in filenames:
if filename.endswith(".png"):
filepath = os.path.join(root, filename)
width, height = Image.open(filepath).size
results[subdirectory].append((filename, width, height))
# Print output
for subdirectory, images in results.items():
print(f"{subdirectory} has {len(images)} image(s):")
for filename, width, height in images:
print(f"{filename} resolution is {width}x{height}")
print()
# Manually write the CSV file
with open("png files.csv", "wt") as f:
f.write("Subdirectory,Filename,Width,Height\n") # Header
for subdirectory, images in results.items():
for filename, width, height in images:
f.write(f"{subdirectory},{filename},{width},{height}\n") # Rows
stdout
输出:
Subfolder1 has 4 image(s):
a.png resolution is 640x480
b.png resolution is 640x480
c.png resolution is 300x300
d.png resolution is 300x300
Subfolder2 has 4 image(s):
a.png resolution is 300x300
b.png resolution is 300x300
c.png resolution is 300x300
d.png resolution is 300x300
Subfolder3 has 4 image(s):
a.png resolution is 300x300
b.png resolution is 300x300
c.png resolution is 26x26
d.png resolution is 300x30
Subfolder4 has 1 image(s):
a.png resolution is 256x240
CSV 文件:
Subdirectory,Filename,Width,Height
Subfolder1,a.png,640,480
Subfolder1,b.png,640,480
Subfolder1,c.png,300,300
Subfolder1,d.png,300,300
Subfolder2,a.png,300,300
Subfolder2,b.png,300,300
Subfolder2,c.png,300,300
Subfolder2,d.png,300,300
Subfolder3,a.png,300,300
Subfolder3,b.png,300,300
Subfolder3,c.png,26,26
Subfolder3,d.png,300,30
Subfolder4,a.png,256,240
用 Microsoft Excel 打开的 CSV 文件:
推荐阅读
- c# - 如何在 C# 中编辑/更新数组列表值
- google-sheets - 仅查询谷歌表中的 nat 空列
- position - 'position()' 是否必须明确包含在此 Xpath 中?
- c - 使用 AES-128-CBC 和 Open SSL EVP 加密(语言 C)
- email - 我正在尝试使用托管在 heroku 上的烧瓶 API 发送一封自动电子邮件,我的 API 在本地主机上运行良好,但在访问时抛出错误
- mongodb - Mongodb在单行中获取计数
- php - 在php中使用邮件功能仅发送文本内容
- c# - 如何通过 Microsoft Graph API 从 driveItem 中删除下载/查看/编辑权限?
- blogger - 如何更改位置加载更多...博客中的评论
- javascript - 如何返回由 4 个对象组成的数组的前 2 个对象