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
8 1541
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: -
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
-
See if that works for you.
Or you could do it without re: -
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(key_value[0])
-
-
print myKeys
-
Try that.
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? - 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).readlines()
-
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).readlines()
-
result = []
-
for item in fileList:
-
if '=' in item:
-
result.append(item.split('=')[0].strip())
-
return result
-
-
print import_data('your_file')
Output:
>>> ['item1', 'item2', 'item3', 'item4']
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.
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']
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: -
['item1 ', ' 100']
-
['item2 ', ' 100']
-
['item3 ', ' 100']
-
['item4 ', ' 100']
-
then you can put them in lists etc...up toyou.
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.
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.. -
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: -
[someitems] [['item1 ', ' 100'], ['item2 ', ' 100'], ['item3 ', ' 100'], ['item4 ', ' 100'], ['']]
-
[moreitems] [['item5 ', ' 700'], ['item6 ', ' 701'], ['item7 ', ' 702']]
-
-
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. - 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]
Sample usage: - print import_key_data('data_file_name', 'someitems')
>>> {'item2': '100', 'item3': '100', 'item1': '100', 'item4': '100'}
>>> ['item1', 'item2', 'item3', 'item4']
Sign in to post your reply or Sign up for a free account.
Similar topics
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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:
...
|
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...
|
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...
|
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=()=>{
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
| |