使用python内置的imghdr模块读取图像文件以修正错误的扩展名

之所以有这个程序是因为做了个爬虫,URL中并没有文件名,默认保存可能无扩展名,然后需要进行修正。本程序遍历工作文件夹和子文件夹的所有文件。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
###
# File: fix_png_suffix.py
# Created Date: 2023-03-21 10:50:08
# Author: Simon Liu
# -----
# Last Modified: 2023-03-23 20:08:13
# Modified By: Simon Liu
# -----
# Copyright (c) 2023 SimonLiu Inc.
# 
# May the force be with you.
# -----
# HISTORY:
# Date      	By	Comments
# ----------	---	----------------------------------------------------------
###

import os,time
import imghdr


# 获取当前工作目录
root_folder = os.getcwd()

def fix_suffix(entry):
	 root, ext = os.path.splitext(entry)
	 type = imghdr.what(entry)
	 ext_no_dot = ext.lstrip(".")
	 if type:  # 如果文件是图片
	     print(f"{entry}是个图像文件,扩展名{ext},实际类型{type}")
	     if ext_no_dot != type:
	         filename = '.'.join([root,type])
	         print(f"⚠️  修正{entry}后缀名,新文件{filename}")
	         os.rename(entry, filename)
	     else:
	         print("文件无需修正")

def recursive_check(root_folder):
    for entry in os.scandir(root_folder):
        if entry.is_dir():
            recursive_check(entry.path)
        elif entry.is_file():
            fix_pic_suffix(entry)
            time.sleep(1)
recursive_check(root_folder)
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值