471,337 Members | 1,342 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,337 software developers and data experts.

Conf data into a list

4
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..ect

Im new to Python so bear with me :/

Thank You
Sep 16 '07 #1
8 1305
ilikepython
844 Expert 512MB
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..ect

Im new to Python so bear with me :/

Thank You
You can do with re:
Expand|Select|Wrap|Line Numbers
  1. import re
  2.  
  3. patt = re.compile(r"""^([\w]+)
  4.                        [ \t]+=[ \t]+
  5.                        ([\w]+)$
  6.                    """, re.VERBOSE | re.MULTILINE)   # to make it look nice
  7.  
  8. s = "item1 = 100\nitem2 = 100\nitem3 = 100\nitem4 = 100"
  9. data = patt.findall(s)
  10. myKeys = [t[0] for t in data]
  11. print myKeys
  12.  
See if that works for you.
Or you could do it without re:
Expand|Select|Wrap|Line Numbers
  1. s = "item1 = 100\nitem2 = 100\nitem3 = 100\nitem4 = 100"
  2. lines = s.split("\n")
  3.  
  4. myKeys = []
  5. for line in lines:
  6.     key_value = [kv.strip() for kv in line.split("=")]
  7.     myKeys.append(key_value[0])
  8.  
  9. print myKeys
  10.  
Try that.
Sep 16 '07 #2
bvdet
2,851 Expert Mod 2GB
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..ect

Im new to Python so bear with me :/

Thank You
Something like this?
Expand|Select|Wrap|Line Numbers
  1. import re
  2.  
  3. def import_data(fn):
  4.     patt = r'(.+)=.+'
  5.     return [item.strip() for item in re.findall(patt, open(fn).read())]
  6.  
  7. # OR
  8. def import_data(fn):
  9.     fileList = open(fn).readlines()
  10.     return [item.split('=')[0].strip() for item in fileList if '=' in item]
  11.  
  12. # Same as above without the list comprehension
  13. def import_data(fn):
  14.     fileList = open(fn).readlines()
  15.     result = []
  16.     for item in fileList:
  17.         if '=' in item:
  18.             result.append(item.split('=')[0].strip())
  19.     return result
  20.  
  21. print import_data('your_file')
Output:
>>> ['item1', 'item2', 'item3', 'item4']
Sep 16 '07 #3
WarFan
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.
Sep 16 '07 #4
WarFan
4
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("items.cfg")
for option in config.options(section):
myitems.append(option)

returns ['item1', 'item2', 'item3', 'item4']
Sep 17 '07 #5
ghostdog74
511 Expert 256MB
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("items.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:
Expand|Select|Wrap|Line Numbers
  1. ['item1 ', ' 100']
  2. ['item2 ', ' 100']
  3. ['item3 ', ' 100']
  4. ['item4 ', ' 100']
  5.  
then you can put them in lists etc...up toyou.
Sep 17 '07 #6
WarFan
4
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.
Sep 17 '07 #7
ghostdog74
511 Expert 256MB
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..
Expand|Select|Wrap|Line Numbers
  1. sections={}
  2. for line in open("file"):
  3.     line=line.strip()
  4.     if line.startswith("#"): continue
  5.     if line.startswith("["):
  6.         s=line
  7.         sections[s]=[]
  8.         continue
  9.     else:
  10.         if line.startswith("["): 
  11.             continue
  12.         else:
  13.             line=line.strip().split("=")
  14.             sections[s].append(line)
  15.  
  16. for i,j in sections.iteritems():
  17.     print i,j
  18.  
output:
Expand|Select|Wrap|Line Numbers
  1. [someitems] [['item1 ', ' 100'], ['item2 ', ' 100'], ['item3 ', ' 100'], ['item4 ', ' 100'], ['']]
  2. [moreitems] [['item5 ', ' 700'], ['item6 ', ' 701'], ['item7 ', ' 702']]
  3.  
  4.  
Sep 17 '07 #8
bvdet
2,851 Expert Mod 2GB
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.
Expand|Select|Wrap|Line Numbers
  1. def import_key_data(fn, key, q=('[',']')):
  2.     f = open(fn)
  3.  
  4.     # skip to key section
  5.     s = f.next()
  6.     while s.strip() != key.join(q):
  7.         s = f.next()
  8.  
  9.     result = []
  10.     for line in f:
  11.         if line.startswith(q[0]):
  12.             break
  13.         else:
  14.             if '=' in line:
  15.                 result.append([item.strip() for item in line.split('=')])
  16.     f.close()
  17.     # return dictionary
  18.     return dict(zip([i[0] for i in result], [j[1] for j in result]))
  19.     # return list of keys
  20.     # return [i[0] for i in result]
Sample usage:
Expand|Select|Wrap|Line Numbers
  1. print import_key_data('data_file_name', 'someitems')
>>> {'item2': '100', 'item3': '100', 'item1': '100', 'item4': '100'}

>>> ['item1', 'item2', 'item3', 'item4']
Sep 17 '07 #9

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by CSN | last post: by
6 posts views Thread by David Nedrow | last post: by
5 posts views Thread by Susemail | last post: by
5 posts views Thread by Raymond O'Donnell | last post: by
reply views Thread by =?Utf-8?B?QWxleA==?= | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.