472,958 Members | 2,335 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,958 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 1541
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

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

Similar topics

1
by: CSN | last post by:
Should "restart" with pg_ctl or /etc/init.d/postgres cause postgres.conf to be reread? It doesn't appear to do so for me (another oddity - after "restart" the last line in the log is "database...
6
by: David Nedrow | last post by:
I'm trying to set up the cyrus imap server using PostgreSQL as the authentication backend. Currently, the issue I'm having is that I'm unable to connect via psql on the loopback address...
5
by: Susemail | last post by:
Is this good advice? IDENT Authentication failed for user "postgres" This error has everything to do with the way distros set up access rights for postgres. They are way too restrictive and...
2
by: Liza | last post by:
Hi, I've just setup postgreSQL on my Fedora Core1 box. I installed postgresql from rpm files. When I try to connect to the postgresql server in pgmanage, or through an ODBC from other windows...
3
by: Si Chen | last post by:
Hello. It seems that every time I make a change to pg_hba.conf, I have to restart the database server for the new authentication to take effect. Is there a way to have the server use the new...
5
by: Raymond O'Donnell | last post by:
Hello all, I've installed the new Win32 version of 8.0-beta1, running as a service. When I connect to it using pgAdmin III and attempt to list databases, I get an error: 'Column "datpath" does...
3
by: smitty1e | last post by:
Just a fun exercise to unify some of the major input methods for a script into a single dictionary. Here is the output, given a gr.conf file in the same directory with the contents stated below: ...
0
by: =?Utf-8?B?QWxleA==?= | last post by:
Hi to everyone At the moment, I am converting a .Net 1.1 application to 2.0. As the My.settings did not exist in the 1.1 framework, the "101 VB.NET Sample" "How to configuration settings" was...
3
by: gjain123 | last post by:
Hi all, I am using netbeans as IDE and glassfish as app server for my web application. At runtime it needs some dll files and .conf file. Now the question is: 1. How should I package the .conf...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
2
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.