我正在为Python 3.2编辑libtaxii的脚本,因为它是为Python 2.7编写的。我正在使用以下函数将内容块写入文件。这是功能:
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'
所以解释器知道它是一个字符串,但它不识别它?我真的不是100%肯定。
提前感谢所有比我聪明的人!
答案 0 :(得分:1)
“可能结果来自for循环中for cb的两个不同迭代。编写代码以便能够将cb.content作为str或bytes对象处理” - 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'))
效果很好。谢谢你们!