2017-08-29 58 views
1

我正在爲Python 3.2編寫libtaxii的腳本,因爲它是爲Python 2.7編寫的。我正在使用以下將內容塊寫入文件的函數。這裏的功能:Python 3.2中TypeError問題的AttributeError

def write_cbs_from_poll_response_11(self, poll_response, dest_dir, write_type_=W_CLOBBER): 

    for cb in poll_response.content_blocks: 
     if cb.content_binding.binding_id == CB_STIX_XML_10: 
      format_ = '_STIX10_' 
      ext = '.xml' 
     elif cb.content_binding.binding_id == CB_STIX_XML_101: 
      format_ = '_STIX101_' 
      ext = '.xml' 
     elif cb.content_binding.binding_id == CB_STIX_XML_11: 
      format_ = '_STIX11_' 
      ext = '.xml' 
     elif cb.content_binding.binding_id == CB_STIX_XML_111: 
      format_ = '_STIX111_' 
      ext = '.xml' 
     elif cb.content_binding.binding_id == CB_STIX_XML_12: 
      format_ = '_STIX12_' 
      ext = '.xml' 
     else: # Format and extension are unknown 
      format_ = '' 
      ext = '' 

     if cb.timestamp_label: 
      date_string = 't' + cb.timestamp_label.isoformat() 
     else: 
      date_string = 's' + datetime.datetime.now().isoformat() 

     filename = gen_filename(poll_response.collection_name, 
           format_, 
           date_string, 
           ext) 
     filename = os.path.join(dest_dir, filename) 
     write, message = TaxiiScript.get_write_and_message(filename, write_type_) 

     if write: 
      with open(filename, 'w') as f: 
       f.write(cb.content)   # The TypeError is thrown here 

     print("%s%s" % (message, filename)) 

我現在的問題是一個變量,cb.content拋出一個錯誤類型:

TypeError: must be str, not bytes 

這是一個簡單的辦法:我用轉換器f.write(cb.content.decode("utf-8"))到位的行,然後它拋出一個AttributeError:

AttributeError: 'str' object has no attribute 'decode' 

所以翻譯知道這是一個字符串,但它不承認它?我並不十分確定。

在此先感謝你們所有比我更聰明的人!

+0

你打印出'cb.contents'的內容嗎? –

+1

可能的結果來自'for for循環中的cb的兩個不同迭代。編寫代碼以便能夠將'cb.content'作爲'str'或'bytes'對象來處理。 – glibdud

+0

我做過;內容可以打印,但我假設,因爲我正在處理一個XML文件,我可能會有一些奇怪的字符。 以下是內容:https://pastebin.com/k2Xed6C9 – Arcsector

回答

1

"Possibly the results are from two different iterations of the for cb in... loop. Write your code to be able to handle cb.content as either a str or bytes object" -- glibdud

Glibdud是絕對正確的。我在下面代替f.write(cb.content)添加了:

if type(cb.content) is str: 
    f.write(cb.content) 
elif type(cb.content) is bytes: 
    f.write(cb.content.decode('utf-8')) 

而且它工作得很好。多謝你們!