Conf data into a list

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • WarFan
    New Member
    • Sep 2007
    • 4

    Conf data into a list

    Hello,

    I'm wanting to learn how to make a list out of data from a conf file.

    In my conf file I have this:

    [someitems]
    item1 = 100
    item2 = 100
    item3 = 100
    item4 = 100

    In my script, it will read the config then I want to put the keys? into a list.
    I then will see if an item is in that list.
    mykeys = ['item1', 'item2', 'item3', 'item4']
    I do not want the values in the list, just the item1,item2..ec t

    Im new to Python so bear with me :/

    Thank You
  • ilikepython
    Recognized Expert Contributor
    • Feb 2007
    • 844

    #2
    Originally posted by WarFan
    Hello,

    I'm wanting to learn how to make a list out of data from a conf file.

    In my conf file I have this:

    [someitems]
    item1 = 100
    item2 = 100
    item3 = 100
    item4 = 100

    In my script, it will read the config then I want to put the keys? into a list.
    I then will see if an item is in that list.
    mykeys = ['item1', 'item2', 'item3', 'item4']
    I do not want the values in the list, just the item1,item2..ec t

    Im new to Python so bear with me :/

    Thank You
    You can do with re:
    [code=python]
    import re

    patt = re.compile(r""" ^([\w]+)
    [ \t]+=[ \t]+
    ([\w]+)$
    """, re.VERBOSE | re.MULTILINE) # to make it look nice

    s = "item1 = 100\nitem2 = 100\nitem3 = 100\nitem4 = 100"
    data = patt.findall(s)
    myKeys = [t[0] for t in data]
    print myKeys
    [/code]
    See if that works for you.
    Or you could do it without re:
    [code=python]
    s = "item1 = 100\nitem2 = 100\nitem3 = 100\nitem4 = 100"
    lines = s.split("\n")

    myKeys = []
    for line in lines:
    key_value = [kv.strip() for kv in line.split("=")]
    myKeys.append(k ey_value[0])

    print myKeys
    [/code]
    Try that.
    Last edited by ilikepython; Sep 16 '07, 09:46 PM. Reason: deleted comments which were included in block string

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Originally posted by WarFan
      Hello,

      I'm wanting to learn how to make a list out of data from a conf file.

      In my conf file I have this:

      [someitems]
      item1 = 100
      item2 = 100
      item3 = 100
      item4 = 100

      In my script, it will read the config then I want to put the keys? into a list.
      I then will see if an item is in that list.
      mykeys = ['item1', 'item2', 'item3', 'item4']
      I do not want the values in the list, just the item1,item2..ec t

      Im new to Python so bear with me :/

      Thank You
      Something like this?[code=Python]import re

      def import_data(fn) :
      patt = r'(.+)=.+'
      return [item.strip() for item in re.findall(patt , open(fn).read() )]

      # OR
      def import_data(fn) :
      fileList = open(fn).readli nes()
      return [item.split('=')[0].strip() for item in fileList if '=' in item]

      # Same as above without the list comprehension
      def import_data(fn) :
      fileList = open(fn).readli nes()
      result = []
      for item in fileList:
      if '=' in item:
      result.append(i tem.split('=')[0].strip())
      return result

      print import_data('yo ur_file')[/code]Output:
      >>> ['item1', 'item2', 'item3', 'item4']

      Comment

      • WarFan
        New Member
        • Sep 2007
        • 4

        #4
        Ok, Ill give it a shot.
        I was thinking there would be an easier way to search for a section and just return the keys. I guess I was way off..lol Thanks, Ill let you know if one of the methods described works.

        Comment

        • WarFan
          New Member
          • Sep 2007
          • 4

          #5
          Ok, after digging around some more and trying different things. This is what I came up with that I was looking to do using ConfigParser. Thanks

          # a section in items.cfg
          [someitems]
          item1 = 100
          item2 = 100
          item3 = 100
          item4 = 100

          section = "someitems"
          myitems = []
          readme = config.read("it ems.cfg")
          for option in config.options( section):
          myitems.append( option)

          returns ['item1', 'item2', 'item3', 'item4']

          Comment

          • ghostdog74
            Recognized Expert Contributor
            • Apr 2006
            • 511

            #6
            Originally posted by WarFan
            Ok, after digging around some more and trying different things. This is what I came up with that I was looking to do using ConfigParser. Thanks

            # a section in items.cfg
            [someitems]
            item1 = 100
            item2 = 100
            item3 = 100
            item4 = 100

            section = "someitems"
            myitems = []
            readme = config.read("it ems.cfg")
            for option in config.options( section):
            myitems.append( option)

            returns ['item1', 'item2', 'item3', 'item4']
            the little "nuisance" i see using configparser is if you config file changes, ie, you added some more items , you have to change your Python script to get those items. ( I could be wrong though as I have not used this module for quite some time). I think its better to code your own little parsing routine so that you don't have to edit your script if your config files changes.eg
            [code]
            for line in open("file"):
            if line.startswith ("#"): continue
            if line.startswith ("["): continue
            else:
            if line.startswith ("["):
            continue
            else:
            line=line.strip ().split("=")
            print line
            [code]
            output:
            Code:
            ['item1 ', ' 100']
            ['item2 ', ' 100']
            ['item3 ', ' 100']
            ['item4 ', ' 100']
            then you can put them in lists etc...up toyou.

            Comment

            • WarFan
              New Member
              • Sep 2007
              • 4

              #7
              That would be ok but I have 7 other sections in the cfg file. Wouldnt that code return them all? Im trying to return a certain section at a time.

              Comment

              • ghostdog74
                Recognized Expert Contributor
                • Apr 2006
                • 511

                #8
                Originally posted by WarFan
                That would be ok but I have 7 other sections in the cfg file. Wouldnt that code return them all? Im trying to return a certain section at a time.
                its just a matter of storing them for later use , isn't it.? You can use dictionaries, list , whatever you find comfortable with..
                Code:
                sections={}
                for line in open("file"):
                    line=line.strip()
                    if line.startswith("#"): continue
                    if line.startswith("["):
                        s=line
                        sections[s]=[]
                        continue
                    else:
                        if line.startswith("["): 
                            continue
                        else:
                            line=line.strip().split("=")
                            sections[s].append(line)
                     
                for i,j in sections.iteritems():
                    print i,j
                output:
                Code:
                [someitems] [['item1 ', ' 100'], ['item2 ', ' 100'], ['item3 ', ' 100'], ['item4 ', ' 100'], ['']]
                [moreitems] [['item5 ', ' 700'], ['item6 ', ' 701'], ['item7 ', ' 702']]

                Comment

                • bvdet
                  Recognized Expert Specialist
                  • Oct 2006
                  • 2851

                  #9
                  Originally posted by WarFan
                  That would be ok but I have 7 other sections in the cfg file. Wouldnt that code return them all? Im trying to return a certain section at a time.
                  Following is another version that will return a specific section. Comment out one of the return statements to return a list or dictionary.[code=Python]def import_key_data (fn, key, q=('[',']')):
                  f = open(fn)

                  # skip to key section
                  s = f.next()
                  while s.strip() != key.join(q):
                  s = f.next()

                  result = []
                  for line in f:
                  if line.startswith (q[0]):
                  break
                  else:
                  if '=' in line:
                  result.append([item.strip() for item in line.split('=')])
                  f.close()
                  # return dictionary
                  return dict(zip([i[0] for i in result], [j[1] for j in result]))
                  # return list of keys
                  # return [i[0] for i in result][/code]
                  Sample usage:[code=Python]print import_key_data ('data_file_nam e', 'someitems')[/code]

                  >>> {'item2': '100', 'item3': '100', 'item1': '100', 'item4': '100'}

                  >>> ['item1', 'item2', 'item3', 'item4']

                  Comment

                  Working...