0
votes

Can someone help me figure out what I'm doing wrong? I'm writing a python shell script that takes an ldif file and a csv file and then appends the contents in the csv file to the end of each record in the ldif. Something like:

Sample CSV:


    "KEY","VALUE"
    "abc","def"
    "foo","bar"
    "qwop","flop"

Sample .ldif:


    dn: Aziz
    cn: Aziz_09

    dn: Carl
    cn: Carl_04

After python myscript.py "sample.ldif" "sample.csv"


    dn: Aziz
    cn: Aziz_09
    KEY: VALUE
    abc: def
    foo: bar
    qwop: flop

    dn: Carl
    cn: Carl_04
    KEY: VALUE
    abc: def
    foo: bar
    qwop: flop

So far my code compiles however it doesn't modify the file correctly. I'm creating an object that takes a csv file path name string on creation and then stores the keys into a list field and stores the values into a list field. I then open the ldif file, parse for the escape characters between records and insert the list fields (KEY and VALUE) at the end of each record:


    import sys, csv

    #  Make new object that can open a csv and set csv data in its arrays
    class Container(object):
      def __init__(self, filename=None, keys=None, values=None):
        self.filename = filename
        self.keys = []
        self.values = []

      #  Opens self.filename and puts 0th and 1st rows into keys and values respectively  
      def csv_to_list():
        with open(self.filename, 'rb') as f:
          reader = csv.reader(f)
          for row in reader:
            self.keys = row[0]
            self.values = row[1]

    haruhi = Container("./content/test_pairs.txt")
    haruhi.csv_to_list

    # open first argument of the command line call to ldif_record_a.py for read/writing
    with open(sys.argv[1],'r+') as f1:
      lines=[x.strip() for x in f1]  # Create list with each line as an element
      f1.truncate(0)
      f1.seek(0)
      count = 0
      for x in lines:
         if x:
           f1.write(x+'\n')
         else:
           f1.write("{0}: {1}\n\n".format(haruhi.keys[count] , haruhi.values[count]))
           count = count + 1
      f1.write("{0}: {1}\n\n".format(haruhi.keys[count] , haruhi.values[count]))

I am new to Python! Any help, advice and/or resource direction would be greatly appreciated! Thank you SO

1
What python version do you use ? - Dmitry Zagorulkin
Instead of self.keys = row[0] I guess you want to say self.keys.append(row[0]) ? - Shaung
@ZagorulkinDmitry I'm using 2.7 - Freddie Julius Monkeyking
@Shuang I'm not sure, could you elaborate? - Freddie Julius Monkeyking
In 2.7 better use string="{}" string.format() - Dmitry Zagorulkin

1 Answers

1
votes

Okay, I adhoc'd this, so it needs work, but here goes:

import csv
import re

csv_data = list(csv.reader(open('/home/jon/tmp/data.csv'))) # (1)
csv_text = '\n' + '\n'.join('{0} : {1}'.format(*row) for row in csv_data) # (2)

with open('/home/jon/tmp/other.ldif') as f:
    contents = f.read() # (3)
    print re.sub(r'(\n\n)|(\n$)', csv_text + '\n\n', contents) # (4)
  • (1) Read the CSV file into a list of lists

    csv_data == [['KEY', 'VALUE'], ['abc', 'def'], ['foo', 'bar'], ['qwop', 'flop']]

  • (2) Create a text representation to be append to each ldif

    KEY : VALUE abc : def foo : bar qwop : flop

  • (3) Open and read the entire contents into memory (not very efficient mind you)

  • (4) Use a regular expression to find the "next bit" after the ldif and put in text

Prints:

dn: Aziz
cn: Aziz_09
KEY : VALUE
abc : def
foo : bar
qwop : flop

dn: Carl
cn: Carl_04
KEY : VALUE
abc : def
foo : bar
qwop : flop

You'll need to adjust it to write data back out or whatever you want..., but is a possible starting point - but strongly recommend you use it a base to work through accompanied by the Python manual. Feel free to ask for any clarification.