Python--将指定目录下的图片 .PNG大写 改为 .png 小写

本文介绍了一个简单的Python脚本,用于批量将指定目录下的图片文件从.PNG格式转换为.png格式。通过使用os模块,该脚本可以轻松地遍历目录并对文件进行重命名。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python--将指定目录下的图片 .PNG大写 改为 .png 小写


以前工作中遇到的问题,用 python解决之,当然我当时参考了 stackoverflow上的问答。

思路无非就是:遍历目录下的文件,获得文件名,然后 rename 。


#!/usr /bin/env python
# encoding: utf-8

import os

# PNG --> png

files = os.listdir(".")
for filename in files:
    file_wo_ext, file_ext = os.path.splitext(filename) #
    if file_ext == ".PNG":
        newfile = file_wo_ext + ".png"
        os.rename(filename, newfile)


#If the current working directory is not cur_dir, it fails. That's because os.listdir() returns only the list of filenames, 
without path. You should change to

#os.rename(os.path.join(cur_dir, filename), os.path.join(cur_dir, newfile))

#os.chdir(r"D:\bossPNG") #指定目录

注: os.listdir() 不会返回路径的。



或者:

#!/usr/bin/env python
# encoding: utf-8

# PNG --> png

import os



cur_dir = "."

for filename in os.listdir(cur_dir):
    file_ext = os.path.splitext(filename)[1]
    if file_ext == '.PNG':
        newfile = filename.replace(file_ext, '.png')
        os.rename(cur_dir+'/'+filename, cur_dir+'/'+newfile)





#If the current working directory is not cur_dir, it fails. That's because os.listdir() returns only the list of filenames,
 without path. You should change to

#os.rename(os.path.join(cur_dir, filename), os.path.join(cur_dir, newfile))

#或者这样用也可以:os.chdir(r"E:\PNG")


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值