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


 

posted @ 2013-10-25 19:08  写程序的⑨  阅读(1639)  评论(0编辑  收藏  举报