import cv2
import os
import time
path='test'
result='test_result'
dir = os.listdir(path)
print('需要压缩的图片数为:'+str(len(dir)))
count = 1
for i in dir:
print('正在压缩第{}张图片'.format(count),end = ',')
start=time.time()
img=cv2.imread(path+'/{}'.format(i))
cv2.imwrite(result+'/{}'.format(i),img,[int(cv2.IMWRITE_JPEG_QUALITY), 10])
end=time.time()
print('压缩第{}张图片耗时{}'.format(count,end-start))
count+=1
2、批量修改图片像素import os
from PIL import Image
import glob
def convertjpg(jpgfile,outdir,width=300,height=225):
img=Image.open(jpgfile)
new_img=img.resize((width,height),Image.BILINEAR)
new_img.save(os.path.join(outdir,os.path.basename(jpgfile)))
for jpgfile in glob.glob("test/*.jpg"):
convertjpg(jpgfile,"test_result")
' 3、批量修改指定目录下文件的名字 方法一:修改为类似cup1.jpg...的格式import os
path = 'test'
count = 1
for i in os.listdir(ipath):
old_name = os.path.join(path, i)
new_name = os.path.join(path, 'cup{}.jpg'.format(count))
count += 1
if count >100: break
os.rename(old_name,new_name)
方法2:修改为类似name_0001.jpg...的格式import os
def formatting(count):
strcount=str(count)
if len(strcount)==1:
return '000'+strcount
elif len(strcount)==2:
return '00'+strcount
elif len(strcount)==3:
return '0'+strcount
elif len(strcount)==4:
return strcount
def rename():
count=0
path='test'
filelist=os.listdir(path)
for files in filelist:
Olddir=os.path.join(path,files)
filename=os.path.splitext(files)[0]
filetype=os.path.splitext(files)[1]
Newdir=os.path.join(path,'name_'+formatting(count)+filetype)
os.rename(Olddir,Newdir)
count+=1
print('success')
rename()
4、删除指定目录下所有文件import os
def del_file(path):
ls = os.listdir(path)
for i in ls:
c_path = os.path.join(path, i)
if os.path.isdir(c_path):
del_file(c_path)
else:
os.remove(c_path)
path = 'test'
del_file(path)
5、删除指定目录下指定后缀的文件import os
import glob
path ='test/*.jpg'
for infile in glob.glob(path):
os.remove(infile)
'