You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用LDIFWriter导出LDAP属性至LDIF文件时遇类型错误求助

问题分析与解决

错误原因

你遇到的TypeError是因为文件打开模式不匹配:

  • 你用文本模式('w')打开文件,文本模式的文件对象只接受字符串类型的写入内容。
  • 但ldif3的LDIFWriter在处理数据时,会将内容编码为bytes类型(如错误栈里的line.encode('ascii')),尝试写入文本文件就会触发类型错误。

修正方案

将文件打开模式改为二进制写入模式('wb'),这样文件对象可以直接接受bytes数据:

connexion.search(search_base=base_dn, search_filter=filtre_ldap, attributes=['*'], search_scope=SUBTREE)
entry = connexion.entries[0] # 仅返回一条结果
dn = entry.entry_dn
attributes = entry.entry_attributes_as_dict
with open(output_ldif, 'wb') as ldiffile:
    writer = LDIFWriter(ldiffile)
    writer.unparse(str(dn), attributes)

方法正确性确认

你的核心逻辑是正确的:通过LDAP查询获取条目、提取DN和属性字典、调用LDIFWriter.unparse()导出LDIF,只是文件打开模式的细节没处理对,修正后即可正常运行。

内容的提问来源于stack exchange,提问作者varlau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 10:10:04