[Tutor] Trying to find a value in a function.

D2 borelan@wanadoo.fr
Sat Mar 15 12:07:01 2003


That's it. Thank's a lot
I appreciated the cookie :),
it's what i called the Relationship_structure, and record_separate is my 
Format_structure

I'd make some changes,

instead of,
 > record_separate = { 'single_line': split_by_line, 'two_line':
 > two_line_records, .... }

i'd use a dictionary of dictionaries :
formatting={'single_line':{'lines_per_record':1, 'field separator':','},
             'two_line_record':{'lines_per_record':2,
             'field_separator':','}}

in the following function, i'd use :
record = ','.join(record) instead of '\n'.join, so each record will be a 
single line of fields to ease the use of 'cookie' and i'll modify the 
function to use 'formatting' instead of record_separate.

Quite final script :
  from some_module import User

#Object importation script
  #this dictionary may be defined by the user via a form.
  cookie = { 'name':0, 'address':1,  'title':2, 'department':3,
             'homedir':4, 'email':5 }

#Formats may be defined by user and stored in this dictionary
  formatting={'single_line':{'lines_per_record':1, 'field
              separator':','}, 'two_line_record':{'lines_per_record':2,
              'field_separator':','}}

  def makeRecords(filetype, text):
     results = []
     text = text.split('\n')
     for i in range(0, len(text), step):
         record = text[i:i+1]
         record = sep.join(record)
         results.append(record)
     return results

  def MakeInstance(klass, fields, cookie):
     instance = klass()
     for attr, index in cookie.items():
         setattr(instance, attr, fields[index])
     return instance


  filetype = 'single_line'
  file_name= 'datafile.txt'
  klass=User

  def importFile(file_name, file_type, klass, cookie)
     infile = file(file_name, 'r')
     text = infile.read()
     infile.close()
     step=formatting[filetype]['lines_per_record']
     sep=formatting[filetype]['field separator']
     lines = makeRecords(filetype, text)
     users = []
     for line in lines:
        fields = line.split(sep)
        instance = MakeInstance(klass, fields, cookie)
        instances.append(instance)
     for each_instance in instances:
        each_instance.do_processing()
     print 'Well done! Thanks to Jeff Shannon'
#

I will post it here in its final version.

Thanks,

Andre