Python LDIF Parser

时间:2014-08-25 02:20:29

标签: python

我正在尝试解析下面的示例LDIF文件中的数据。我想只写出' LoginID'的值。和邮件' csv文件中的参数。

dn: uid=123456789012345,ou=Students,o=system.edu,o=system
LoginId: 0012345
mail: test1@test.edu

dn: uid=543210987654321,ou=Students,o=system.edu,o=system
LoginId: 0067890
mail: test2@test.edu

以下是我在编译时遇到问题的代码

import csv
from ldif import LDIFParser

class ParseRecords(LDIFParser):
    def __init__(self,infile,csv_writer):
        self.csv_writer = csv_writer
    def handle(self,dn,entry):
        self.csv_writer.writerow([entry['LoginId'],entry['mail']])

with open('/root/Python_Scripts/LDIF','rb') as infile, open('/root/Python_Scripts/LDIFExtract.csv','wb') as outfile:
    csv_writer = csv.writer(outfile)
    csv_writer.writerow(['LoginId','mail'])
    ParseRecords(infile,csv_writer).parse()

编译代码时,出现错误

Traceback (most recent call last):
  File "LDIFExtract.py", line 14, in <module>
    ParseRecords(infile,csv_writer).parse()
  File "/usr/lib/python2.7/dist-packages/ldif.py", line 345, in parse
    self._line = self._input_file.readline()
AttributeError: ParseRecords instance has no attribute '_input_file'

感谢您解决此问题的任何帮助。

由于

1 个答案:

答案 0 :(得分:2)

您正在覆盖您继承的类的__init__函数(LDIFParser),其中可能包含self._input_file = infile之类的内容。您可以通过在构造函数中调用LDIFParser.__init__(self, <the arguments that it would use>)或者首先不覆盖构造函数来在类中运行构造函数命令。