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")