2017-02-15 152 views
1

我想保存()由requests.get得到的圖像文件時「FileNotFoundError:[錯誤2]沒有這樣的文件或目錄」試圖寫入文件

def get_image_file(class_path,image_id): 
    r = requests.get(BASE_REQUEST_URL+'/image/'+image_id+'/download', stream=True) 
    print(r.url) 
    if r.status_code == 200: 
     with open(IMAGE_PATH+class_path+str(INCR)+'.jpg', 'wb+') as f: 
      r.raw.decode_content = True 
      shutil.copyfileobj(r.raw, f) 
      print("Image saved") 
    else: 
     print('Can not save the image.') 

所以,如果圖像是良性,圖像將轉至「良性」文件夾。 當我調用該函數

get_image_file('benign/','5436e3acbae478396759f0d5') 

在這裏我得到什麼:

https://isic-archive.com/api/v1/image/5436e3acbae478396759f0d5/download 
Traceback (most recent call last): 
File "image_fetch.py", line 59, in <module> 
    get_image_file('benign/','5436e3acbae478396759f0d5') 
File "image_fetch.py", line 34, in get_image_file 
    with open(IMAGE_PATH+class_path+str(INCR)+'.jpg', 'wb+') as f: 
FileNotFoundError: [Errno 2] No such file or directory: '~/tf_files/benign/0.jpg' 

我想這個問題是在寫permission.I試圖用 'WB', 'WB +', 'A +' ,但沒有任何幫助。

+1

什麼是IMAGE_PATH','class_path'和'INCR' – ZdaR

+1

的'值的文件名似乎:如果你想在波浪線的路徑在Python,你應該通過os.path.expanduseropen之前運行這些從一個引號開始'''(你可以看到沒有關閉的)。複製郵件錯誤時是錯誤還是文件名的引用部分? –

+0

IMAGE_PATH ='〜/ tf_files /',class_path ='良性/',INCR = 0是遞增每次下載的圖像以計算圖像的增量。 – dulatus

回答

1

~/tf_files不是一個有效的路徑,除非你在shell中工作; ~bash和co。擴展到您的主目錄,而非OS。

path = IMAGE_PATH+class_path+str(INCR)+'.jpg' 
path = os.path.expanduser(path) 
with open(path, 'wb+') as f: 
    # ... 
    pass 
相關問題