错误:文件存在时使用Image.open拒绝权限

时间:2019-02-27 13:32:50

标签: python-3.x image python-imaging-library

我发现类似的主题涉及同一问题,但我没有任何解决方案。

我正在Windows 7上使用python 3.7。

我正在使用Flickr的API查询提供关键字的图像。拥有网址后,我将使用PIL下载文件。我以管理员身份运行以下文件:

import flickrapi
import urllib
import urllib.request
from PIL import Image
from datetime import datetime

key='XXX'
mdp='XX'
#Flickr api access key 
flickr=flickrapi.FlickrAPI(key,mdp, cache=True)

#We are going to use two parameters : min_upload_date and max_upload_date to get more images. It has timestamp type 

def query_imgs(keyword,min_upload_date,max_upload_date): 
    imgs = flickr.photos.search(text=keyword,
                 tag_mode='all',
                 tags=keyword,
                 extras='url_c',
                 per_page=500,
                 sort='relevance',
                 min_upload_date=min_upload_date,
                 max_upload_date=max_upload_date,
                 privacy_filter=1,
                 relevance=1)
    return imgs[0]

def get_urls(imgs):
    urls = []
    for img in imgs:
        url = img.get('url_c')
        if (url != None):
            urls.append(url)
    urls=list(set(urls))
    nb_imgs=len(urls)
    return  (urls,nb_imgs)

def get_imgs(urls,keyword,count):
    for i in range(len(urls)):
        filename=keyword+'.'+str(count+i)+'.jpg'
        urllib.request.urlretrieve(urls[i], filename)
        image = Image.open(filename,'r') 
        image = image.resize((256, 256), Image.ANTIALIAS)
        image.save(filename)

def compute_timestamp(year):
"""Giving the year, return two timestamp correspond to the first day of January and February."""
    dt1=datetime(year,1,1)
    ts1=datetime.timestamp(dt1)
    dt2=datetime(year,2,1)
    ts2=datetime.timestamp(dt2)
    return ts1,ts2

years=[2013,2014,2015,2016,2017,2018]

 def main(keyword):
    count=0
    for year in years : 
        y,z=compute_timestamp(year)
        for i in range(11): 
            imgs=query_imgs(keyword,y+i*2764800,z+i*2678400)
        #2764800 correspond to 32 days, 2678400 to 31 days 
        #Ex : first period : 01/01 to 02/01, then 02/02 to 03/01 (approximatively)
            (urls,x)=get_urls(imgs)
            get_imgs(urls,keyword,count)
            count=count+x
            print(count,"Next Month")
    print("Next year")






main('Violence')

python文件在我的H:\ EmotionDetection中。我以管理员身份运行。

有时候,我没有错误。但是经常会出现以下错误:

enter image description here

这很奇怪,因为它可以处理1500多个图像。该文件位于文件夹中,但是当我尝试调整其大小时不起作用。

有没有人知道如何修改我的代码以便可以正常工作?

提前谢谢

0 个答案:

没有答案