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
self.keys = row[0]I guess you want to sayself.keys.append(row[0])? - Shaung