[Tutor] (no subject)

Glen Bunting Glen@ihello-inc.com
Wed, 21 Mar 2001 13:41:49 -0800


When I try :

>>> import string
>>> CONFIG = open('webconf.txt').read()
>>> for 1 in CONFIG:
...     key, value = string.split(1, ';')
...     print 'The key is : ', key
...     print 'The value is : ', value

SyntaxError: Can't assign to literal

Thanks

Glen 



-----Original Message-----
From: Daniel Yoo [mailto:dyoo@hkn.eecs.berkeley.edu]
Sent: Wednesday, March 21, 2001 12:25 PM
To: Glen Bunting
Cc: 'tutor@python.org'
Subject: Re: [Tutor] (no subject)


On Wed, 21 Mar 2001, Glen Bunting wrote:

> I just wrote my first python program that works.  I am happy.  I am also
> trying to figure out how to make it better.  One of the things that I have
> done is hard code a dictionary in the program.  I am trying to get it to
> read from a config file that I have created which has two values in it, a
> server name and a url.  I have seperated them with a ;.  How can I get
> python to read from the file and use the first value as a ky ant the
second
> as a value and enter it into a dictionary?  I can get it to read in the
file
> but when I try to use re.split or string.split and then print out the
value,
> it only prints out the ;.  Any help would be appreciated.

Using string.split is the right idea.  Here's a small interpreter session
that plays around with string.split():

###
>>> myinput = '''name ; glen
... mailing list ; tutor@python.org'''
>>> import string
>>> lines = string.split(myinput, '\n')
>>> lines
['name ; glen', 'mailing list ; tutor@python.org']
>>> for l in lines:
...     name, value = string.split(l, ';')
...     print "The name is: ", name
...     print "The value is: ", value
...
The name is:  name
The value is:   glen
The name is:  mailing list
The value is:   tutor@python.org
###

Before inserting in your dictionary, let's make make sure that the
splitting is working ok.  If you want, you can show us what you have, and
we can see why it's not splitting well.

Also, it might be necessary to "strip" your keys and values: using
string.strip() on both the keys and values might be a good thing, to get
rid of the leading and trailing whitespace.


Oh, also, if you want to be really fancy, there's a module called the
"ConfigParser" that does name/value pair stuff.  The documentation for it
is here:

    http://python.org/doc/current/lib/module-ConfigParser.html

but it's definitely overkill for your application.

Good luck to you.