PIL不能关闭文件的解决方案

今天写了一个能指定图片尺寸,以及比例 来搜索分类图片的Python脚本。为了读取多个格式的文件的头,采用了Python PIL库。

im = PIL.Image.open(imPath)
if im的属性满足条件:
    os.move(imPath,newPath)

出现了文件被占用的错误。查看PIL的Image模块的文档,发现没有close方法。但是它却占用了文件。这实在是蛋疼。

解决方案如下:

imFp = open(imPath,"rb")
im = PIL.Image.open(imFP)
if im的属性满足条件:
    imFp.close()
    os.move(imPath,newPath)
else:
    imFp.close()


另外给出这个脚本的代码:

import os;
import os.path;
import PIL.Image as Image;
import shutil
import sys
reload(sys)
sys.setdefaultencoding('gb18030')
wkPath = os.getcwd()
allImagesNames = \
             [imPath for imPath in os.listdir(wkPath) \
              if (os.path.isfileth+os.sep+imPath) and \
                  (os.path.splitext(imPath)[1].lower() in [".jpg",".jpeg",".tiff",".png",".gif",".bmp"]))]
minAspect = 0.0
maxAspect = 200.0
minWidth = 0
maxWidth = 1000
minHeight = 0
maxHeight = 1000

outDir = "Aspect_from"+("%.2f" %minAspect)+"to"+("%.2f" %maxAspect)\
+"Dim from"+str(minWidth)+"x"+str(minHeight)+" to "+str(maxWidth)+"x"+str(maxHeight)
for imName in allImagesNames:
    fp = open(wkPath+os.sep+imName,"rb")
    print imName
    im = Image.open(fp)
    w = im.size[0]
    h = im.size[1]
    aspect = float(w)/h
    
    fp.close()
    if aspect<=(maxAspect+0.02) and aspect>=(minAspect-0.02) and w<=maxWidth and w>=minWidth and h<=maxHeight and h>=minHeight:
        if not os.path.exists(wkPath+os.sep+outDir):
            os.mkdir(wkPath+os.sep+outDir)
        shutil.move(wkPath+os.sep+imName,wkPath+os.sep+outDir)
        #print "success"
    else:
        pass


 

转载于:https://www.cnblogs.com/tlm1992/p/3388442.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值