2013-08-15 29 views
15

Sự cố tôi gặp phải là khi tôi cố gắng tải đối tượng pickled. Tôi đã cố gắng sử dụng cả hai pickle.loadspickle.load Dưới đây là kết quả:Không thể nạp đối tượng được ngâm

pickle.loads - TypeError: 'str' does not support the buffer interface

pickle.load - TypeError: file must have 'read' and 'readline' attributes

Có thể ai đó xin vui lòng cho tôi biết những gì tôi đang làm sai trong quá trình này? Cảm ơn, và đây là mã của tôi:

elif str(parser) == 'SwissWithdrawn_Parser': 
     # swissprot name changes 
     print('Gathering SwissProt update info...') 
     cache_hits = 0 
     cache_misses = 0 
     files = set() 

     for f in os.listdir('out/cache/'): 
      if os.path.isfile('out/cache/'+f): 
       files.add(f) 

     for name in sp_lost_names: 

      cached = False 
      url = 'http://www.uniprot.org/uniprot/?query=mnemonic%3a'+name+ \ 
       '+active%3ayes&format=tab&columns=entry%20name' 
      hashed_url = str(hash(url)) 

      ################### For Testing Only - use cache ################## 
      if hashed_url in files: 
       cached = True 
       cache_hits += 1 
       content = pickle.loads('out/cache/' +hashed_url) # <-- problematic line 
      else: 
       cache_misses += 1 
       content = urllib.request.urlopen(url) 

      # get the contents returned from the HTTPResponse object 
      content_list = [x.decode().strip() for x in content.readlines()] 
      if not cached: 
       with open('out/cache/'+hashed_url, 'wb') as fp: 
        pickle.dump(content_list, fp) 
      #################################################################### 

      # no replacement 
      if len(content_list) is 0: 
       change_log['swiss-names'] = 
        { name : 'withdrawn' } 
      # get the new name 
      else: 
       new_name = content_list[1] 
       change_log['swiss-names'] = 
        { name : new_name } 

Trả lời

27

Bạn cần phải hoặc đọc file đầu tiên (như nhị phân bytes) và sử dụng pickle.loads(), hoặc vượt qua một đối tượng tập tin mở cho lệnh pickle.load(). Tùy chọn thứ hai là thích hợp hơn:

with open('out/cache/' +hashed_url, 'rb') as pickle_file: 
    content = pickle.load(pickle_file) 

Cả hai phương pháp đều không hỗ trợ tải dưa chuột từ tên tệp.

+0

Cảm ơn bạn, nhờ câu trả lời của bạn tôi cuối cùng đã có thể thực hiện bộ nhớ cache đầu tiên của mình! :) – Houdini

Các vấn đề liên quan