flying-wyf

python编程快速上手之第17章实践项目参考答案(17.7.2)

#! python3
# Import modules and write comments to describe this program.
import zipfile, os
from PIL import Image
from PIL import ImageFile

#os.chdir('D:\\My Documents\\')
ImageFile.LOAD_TRUNCATED_IMAGES = True
for foldername, subfolders, filenames in os.walk('D:\\My Documents\\'):
  numPhotoFiles = 0
  numNonPhotoFiles = 0
  for filename in filenames:
  # Check if file extension isn't .png or .jpg.
    if not (filename.endswith('.png') or filename.endswith('.jpg') \
        or filename.endswith('.PNG') or filename.endswith('.JPG')\
            or filename.endswith('.gif')or filename.endswith('.GIF')):
      numNonPhotoFiles += 1
      continue # skip to next filename
# Open image file using Pillow.
    os.chdir(foldername)
    try:
      im = Image.open(filename)    
      im = im.convert('RGB')
      width, height = im.size
    except:
      continue
# Check if width & height are larger than 500.
    if max(width,height) > 500 :
# Image is large enough to be considered a photo.
      numPhotoFiles += 1
    else:
# Image is too small to be a photo.
      numNonPhotoFiles += 1
# If more than half of files were photos,
# print the absolute path of the folder.
  if numPhotoFiles > 10 and numPhotoFiles > numNonPhotoFiles:
    print(foldername)

 

posted on 2017-06-06 23:36  flying-wyf  阅读(188)  评论(0)    收藏  举报

导航