2014-02-19 3 views
0

, пожалуйста, помогите исправить сценарий.Как закрыть файл после записи?

import urllib 
import re 
import os 
import pprint 

import requests 
import bs4 


def make_catalog(): 
    try: 
     os.mkdir('GRAB') 
    except FileExistsError: 
     print('FileExistsError') 
    except PermissionError : 
     print('PermissionError ') 
    except Exception: 
     print(Exception)     


def change_catalog(): 
    try: 
     os.chdir('GRAB') 
    except PermissionError : 
     print('PermissionError ') 
    except Exception: 
     print(Exception) 


def download_image(path, name): 
    #urllib.URLopener().retrieve(prefix + path, name) 
    img = urllib.request.urlopen(prefix + path).read() 
    try: 
     f = open(name, "wb") 
     if f: 
      print('open!!!') 
     if f.write(img): 
      print('write!!!') 
    except OSError: 
     print('OSError') 
    except Exception: 
     print(Exception)  
    finally: 
     f.close() 


beginIndex = 5794 
endIndex = 5800 
prefix = "http://www.inpic.ru" 
rep_chars = ['\\', '/', ':', '*', '?', '"', '<', '>', '|', '-' , ' '] 
make_catalog() 
change_catalog() 

for i in range(beginIndex, endIndex): 
    req = requests.get(prefix + '/image/' + str(i)) 
    if req.status_code == requests.codes.ok: 
     #print(i, '\t', req.status_code, '\t', req, end='\n') 
     soup = bs4.BeautifulSoup(req.content) 
     #print(soup.prettify()) 
     name = soup.find("td", {"class": "post_title"}).contents[1].contents 
     #author = soup.find("div", {"class": "date_author"}).contents[1].contents 
     print('NAME: ', name[0]) 
     #print(author[0]) 

     #name[0] = re.sub('[\\\\/:*?"<>|-]', '_', name[0]) 
     for char in rep_chars: 
      name[0] = name[0].replace(char, '_') 

     print('newNAME: ', name[0]) 

     mainImagePath = soup.find("img", {"class": "image last"})["src"] 
     mainImageExt = mainImagePath.split('.')[-1] 
     manyImages = soup.findAll("img", {"class": "image"}) 

     print('MAINUMAGE: ', mainImagePath) 
     print('MAINIMAGE EXT: ',mainImageExt) 
     print('MANYIMAGE: \n') 
     pprint.pprint(manyImages) 

     if len(manyImages) > 1: 
      print('CATALOG MAKE') 
      try: 
       os.mkdir(name[0]) 
      #except FileExistsError: 
       #print('FileExistsError') 
      except PermissionError : 
       print('PermissionError') 
      except Exception: 
       print(Exception)     

      os.chdir(name[0]) 
      #download_image(mainImagePath, str(name[0]) + '_0.' + mainImageExt) 
      i = 0 
      for name in manyImages: 
       #print(name['src'], end='------------\n') 
       download_image(name['src'], str(name['src'])) 
       i = i + 1 
      os.chdir('../') 

     else: 
      print('IMAGE MAKE') 
      download_image(mainImagePath, str(name[0]) + '.' + mainImageExt) 
      print('mainImagePath', mainImagePath) 
      print('name', str(name[0]) + '.' + mainImageExt) 

     print('==================================') 

проблема, что при записи изображений из группы страниц http://www.inpic.ru/image/5797/

отображается следующее сообщение об ошибке:

Traceback (most recent call last): 
    File "C:\VINT\OPENSERVER\OpenServer\domains\localhost\python\parse_html\1\q.py", line 98, in <module> 
    download_image(name['src'], str(name['src'])) 
    File "C:\VINT\OPENSERVER\OpenServer\domains\localhost\python\parse_html\1\q.py", line 46, in download_image 
    f.close() 
UnboundLocalError: local variable 'f' referenced before assignment 

ответ

6

Вы пытаетесь закрыть файл, который не удалось открыть. f никогда не назначался, потому что вызов open() вызвал исключение.

Вместо того чтобы закрыть объект файла в finally обработчика, используйте его в качестве менеджера контекста:

def download_image(path, name): 
    #urllib.URLopener().retrieve(prefix + path, name) 
    img = urllib.request.urlopen(prefix + path).read() 
    try: 
     with open(name, "wb") as f: 
      print('open!!!') 
      f.write(img) 
      print('write!!!') 
    except OSError: 
     print('OSError') 
    except Exception: 
     print(Exception)  

Здесь with заявление будет гарантировать, что f закрыт для вас, если он был успешно открыт, что бы ни случилось.

+0

Спасибо. но по какой-то причине невозможно открыть файл? – Sergey

+0

Удалите только обработчики, и Python скажет вам, почему. –

+0

@Sergey: что означает 'mainImagePath'? Это допустимое имя файла? –

Смежные вопросы