您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python如何读取文件夹中图片的图片名并写入Excel表格
## 前言
在日常工作和数据处理中,我们经常需要批量处理文件夹中的图片文件,并将相关信息(如图片名称、路径、大小等)记录到Excel表格中。这种自动化操作可以大大提高工作效率,减少人工操作的错误。本文将详细介绍如何使用Python实现这一功能。
## 准备工作
在开始之前,我们需要安装一些必要的Python库:
- `os`:用于文件和目录操作(Python内置库,无需安装)
- `openpyxl`:用于操作Excel文件
- `Pillow`(可选):用于获取图片的尺寸等额外信息
可以通过以下命令安装这些库:
```bash
pip install openpyxl Pillow
import os
from openpyxl import Workbook
from openpyxl.styles import Font
from PIL import Image # 可选,用于获取图片尺寸
# 设置图片文件夹路径(请替换为你的实际路径)
image_folder = r"C:\Users\YourName\Pictures\SampleImages"
def get_image_files(folder_path):
"""获取文件夹中所有图片文件"""
image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff']
image_files = []
for file in os.listdir(folder_path):
if os.path.splitext(file)[1].lower() in image_extensions:
image_files.append(file)
return sorted(image_files) # 按名称排序
def create_excel_workbook():
"""创建Excel工作簿"""
wb = Workbook()
ws = wb.active
ws.title = "图片信息"
# 设置标题行
headers = ["序号", "图片名称", "文件大小(KB)", "宽度(像素)", "高度(像素)", "创建时间"]
for col_num, header in enumerate(headers, 1):
cell = ws.cell(row=1, column=col_num, value=header)
cell.font = Font(bold=True)
return wb, ws
def get_image_details(image_path):
"""获取图片的详细信息"""
try:
with Image.open(image_path) as img:
width, height = img.size
except Exception as e:
print(f"无法读取图片信息: {image_path}, 错误: {e}")
width, height = 0, 0
file_size = os.path.getsize(image_path) / 1024 # 转换为KB
create_time = os.path.getctime(image_path)
return {
"width": width,
"height": height,
"size": round(file_size, 2),
"create_time": create_time
}
def write_to_excel(ws, image_files, folder_path):
"""将图片信息写入Excel"""
from datetime import datetime
for row_num, image_file in enumerate(image_files, 2):
image_path = os.path.join(folder_path, image_file)
details = get_image_details(image_path)
# 写入数据
ws.cell(row=row_num, column=1, value=row_num-1) # 序号
ws.cell(row=row_num, column=2, value=image_file) # 图片名称
ws.cell(row=row_num, column=3, value=details["size"]) # 文件大小
ws.cell(row=row_num, column=4, value=details["width"]) # 宽度
ws.cell(row=row_num, column=5, value=details["height"]) # 高度
# 格式化时间
create_time = datetime.fromtimestamp(details["create_time"])
ws.cell(row=row_num, column=6, value=create_time.strftime("%Y-%m-%d %H:%M:%S"))
def adjust_column_width(ws):
"""自动调整Excel列宽"""
from openpyxl.utils import get_column_letter
for col in ws.columns:
max_length = 0
column = col[0].column_letter # 获取列字母
for cell in col:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = (max_length + 2) * 1.2
ws.column_dimensions[column].width = adjusted_width
def main():
# 检查文件夹是否存在
if not os.path.exists(image_folder):
print(f"错误:文件夹 '{image_folder}' 不存在!")
return
# 获取所有图片文件
image_files = get_image_files(image_folder)
if not image_files:
print("警告:没有找到任何图片文件!")
return
print(f"找到 {len(image_files)} 张图片")
# 创建Excel工作簿
wb, ws = create_excel_workbook()
# 写入数据
write_to_excel(ws, image_files, image_folder)
# 调整列宽
adjust_column_width(ws)
# 保存Excel文件
excel_file = os.path.join(image_folder, "图片信息.xlsx")
wb.save(excel_file)
print(f"图片信息已保存到: {excel_file}")
if __name__ == "__main__":
main()
以下是完整的Python脚本:
import os
from openpyxl import Workbook
from openpyxl.styles import Font
from PIL import Image
from datetime import datetime
# 设置图片文件夹路径
image_folder = r"C:\Users\YourName\Pictures\SampleImages"
def get_image_files(folder_path):
"""获取文件夹中所有图片文件"""
image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff']
image_files = []
for file in os.listdir(folder_path):
if os.path.splitext(file)[1].lower() in image_extensions:
image_files.append(file)
return sorted(image_files)
def create_excel_workbook():
"""创建Excel工作簿"""
wb = Workbook()
ws = wb.active
ws.title = "图片信息"
headers = ["序号", "图片名称", "文件大小(KB)", "宽度(像素)", "高度(像素)", "创建时间"]
for col_num, header in enumerate(headers, 1):
cell = ws.cell(row=1, column=col_num, value=header)
cell.font = Font(bold=True)
return wb, ws
def get_image_details(image_path):
"""获取图片的详细信息"""
try:
with Image.open(image_path) as img:
width, height = img.size
except Exception as e:
print(f"无法读取图片信息: {image_path}, 错误: {e}")
width, height = 0, 0
file_size = os.path.getsize(image_path) / 1024
create_time = os.path.getctime(image_path)
return {
"width": width,
"height": height,
"size": round(file_size, 2),
"create_time": create_time
}
def write_to_excel(ws, image_files, folder_path):
"""将图片信息写入Excel"""
for row_num, image_file in enumerate(image_files, 2):
image_path = os.path.join(folder_path, image_file)
details = get_image_details(image_path)
ws.cell(row=row_num, column=1, value=row_num-1)
ws.cell(row=row_num, column=2, value=image_file)
ws.cell(row=row_num, column=3, value=details["size"])
ws.cell(row=row_num, column=4, value=details["width"])
ws.cell(row=row_num, column=5, value=details["height"])
create_time = datetime.fromtimestamp(details["create_time"])
ws.cell(row=row_num, column=6, value=create_time.strftime("%Y-%m-%d %H:%M:%S"))
def adjust_column_width(ws):
"""自动调整Excel列宽"""
from openpyxl.utils import get_column_letter
for col in ws.columns:
max_length = 0
column = col[0].column_letter
for cell in col:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = (max_length + 2) * 1.2
ws.column_dimensions[column].width = adjusted_width
def main():
if not os.path.exists(image_folder):
print(f"错误:文件夹 '{image_folder}' 不存在!")
return
image_files = get_image_files(image_folder)
if not image_files:
print("警告:没有找到任何图片文件!")
return
print(f"找到 {len(image_files)} 张图片")
wb, ws = create_excel_workbook()
write_to_excel(ws, image_files, image_folder)
adjust_column_width(ws)
excel_file = os.path.join(image_folder, "图片信息.xlsx")
wb.save(excel_file)
print(f"图片信息已保存到: {excel_file}")
if __name__ == "__main__":
main()
openpyxl.drawing.image.Image
将缩略图插入到Excel中get_image_files
函数,使用os.walk
遍历子文件夹通过本文介绍的方法,你可以轻松地使用Python自动化处理文件夹中的图片信息,并将其整理到Excel表格中。这种方法不仅适用于图片,稍作修改也可以用于其他类型的文件管理。自动化处理可以显著提高工作效率,减少重复劳动。
希望本文对你有所帮助!如果有任何问题或建议,欢迎留言讨论。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。