![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#11 |
|
Programming Guru
![]() |
Was there something wrong with mine?
![]() Just do some simple modifications on it to suit your needs. It should work fine. I don't see why not? |
|
|
|
|
|
#12 |
|
Expert Programmer
|
I need to be able to store and read tuples, so TUPLE=one,two,three corresponds to ('one', 'two', 'three'). However, I may use your code after making this and other modifications, if I can't get ConfigParser to work.
Also, no one answered one of my previous questions--Is it possible to somehow extract the names of the variables in the ConfigParser file? |
|
|
|
|
|
#13 |
|
Programming Guru
![]() |
Does this help?
def cut_space(item):
for char in range(len(item)):
if item[char] != ' ':
value = item[char:]
break
return value
def str_reverse(item):
value = ''
for char in item:
value = char+value
return value
class conf:
def __init__(self, filename):
self.CONF_FILE = filename
def save(self, opts):
data = []
for key in opts:
value = opts[key]
typekey = type(value)
if typekey == tuple or typekey == list:
value = ', '.join([str(item) for item in value])
data.append('%s = %s'%(key, value))
stream = open(self.CONF_FILE, 'w')
stream.write('\n'.join(data))
stream.close()
def load(self):
stream = open(self.CONF_FILE, 'r')
data = stream.read().split('\n') # readlines keeps the \n there, I don't like that
stream.close()
opts = dict()
for line in data:
newline = line.split('=', 1)
if len(newline) < 2:
raise Exception, 'A line without an equal sign was found'
key = str_reverse(newline[0])
key = cut_space(key) # we are cutting space backwards, since the equal sign is on the right
key = str_reverse(key)
values = newline[1].split(',')
newvalues = list()
for value in values:
newvalue = cut_space(value)
try:
newvalue = int(newvalue)
except ValueError: pass
newvalues += [newvalue]
if len(newvalues) > 1:
opts[key] = tuple(newvalues)
else:
opts[key] = newvalues[0]
return opts
if __name__ == '__main__':
data = conf('options.conf')
data.save( {'level' : 4,
'volume' : 9,
'graphics' : 'high',
'event' : 4112,
'position' : (123, 134),
'names' : 'saney, titaniumdeocy,arevos, Cerulean',
'list' : ['accept', 'my list', 'as well']} )
options = data.load()
print options['graphics']
print options['position']
print options['list']Last edited by Sane; Jul 11th, 2006 at 8:51 PM. |
|
|
|
|
|
#14 |
|
Expert Programmer
|
Thanks, Sane. That looks good. I'll try it out and tell you how it goes.
![]() EDIT: *Mr. Burns voice* Excellent... Last edited by titaniumdecoy; Jul 11th, 2006 at 11:50 PM. |
|
|
|
|
|
#15 |
|
Expert Programmer
|
@Sane: I made some minor changes to your code. I couldn't figure out the purpose of the cut_space or str_reverse functions so I got rid of them--FYI, neither the keys nor values should contain spaces. I also simplified the rest as much as I could. In case you're interested (it's your code, after all), I posted the result below. It works great, although it's too bad it has to rewrite the entire file every time it's saved.
def forcetype(string):
if '.' in string:
try: return float(string)
except ValueError: pass
try: return int(string)
except ValueError: pass
return string
class Conf:
def __init__(self, filename):
self.CONF_FILE = filename
def save(self, opts):
data = []
for key in opts:
value = opts[key]
if type(value) in (tuple, list):
value = ', '.join([str(item) for item in value])
data.append('%s = %s'%(key, value))
stream = open(self.CONF_FILE, 'w')
stream.write('\n'.join(data))
stream.close()
def load(self):
stream = open(self.CONF_FILE, 'r')
data = stream.read().split('\n')
stream.close()
opts = dict()
for line in data:
newline = line.split('=', 1)
key = newline[0].strip()
values = [forcetype(v.strip()) for v in newline[1].split(',')]
opts[key] = len(values) > 1 and tuple(values) or values[0]
return opts |
|
|
|
|
|
#16 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
Any time you modify a file (rather than merely append), you generally wind up rewriting the whole thing. There are ways to get around it but the effort, if you aren't working at a low level (knowledge and access at the file-system level or drive level) is rarely worth it. There's certainly no performance benefit and the resource benefits range from zilch to niggling.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
|
#17 |
|
Programming Guru
![]() |
There were purposes for the cut_space and str_reverse functions. If you read one of the comments in the code, it said...
# we are cutting space backwards, since the equal sign is on the right And we need to cut the space, to handle several different possibilities for how the user could have changed the file. position1 = x, y position2 = x,y position3= x, y position4= x,y position5 =x, y position6 =x,y position7=x, y position8=x,y The code needs to be able to handle any of those 8 basic variations. As well as any extentions upon them as well (EG, two spaces). Then it needs to produce the exact same result. When you allow the user to have manual control of data files, you've put your data at the risk of the user's lack of perfection. To make things short, my code does that, yours does not. Just try copy pasting that in to your configuration file, and see if position1-8 all output the same thing.And one more thing, I see you took out the exception handling. Even though it will be caught on this line... values = [forcetype(v.strip()) for v in newline[1].split(',')] |
|
|
|
|
|
#18 |
|
Expert Programmer
|
@Sane: What's the difference between "cutting spaces" from each side and simply calling the strip function (or lsrip/rstrip), which is what my code does? The output from pasting that snippet into my configuration file is the same as yours:
>>> for key in options: print key, options[key]
position8 ('x', 'y')
position2 ('x', 'y')
position3 ('x', 'y')
position1 ('x', 'y')
position6 ('x', 'y')
position7 ('x', 'y')
position4 ('x', 'y')
position5 ('x', 'y') |
|
|
|
|
|
#19 |
|
Programming Guru
![]() |
Oh wow... I actually had no clue at all that ' asd '.strip() would output 'asd'.
Learned something new. ![]() |
|
|
|
|
|
#20 |
|
Expert Programmer
|
Hmph. I just noticed that Python dicts save their contents in what appears to be pseudo-random order:
>>> print { 'd': 4, 'a': 1, 'b': 2, 'c': 3 }
{'a': 1, 'c': 3, 'b': 2, 'd': 4}I somehow need to preserve the order of variables stored in the configuration file, along with the relative position of comments. |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Storing Data | crawforddavid2006 | C++ | 11 | Jun 24th, 2006 12:41 PM |
| Storing passed information into a text file | dunowhodoyou | PHP | 9 | May 8th, 2006 10:29 AM |
| Storing variables to a file? | Oddball | PHP | 2 | Mar 21st, 2006 2:09 PM |
| Storing Negative Numbers in unsigned ints | aznluvsmc | C | 9 | Aug 22nd, 2005 10:09 PM |
| Language preferences | peace_of_mind | Coder's Corner Lounge | 7 | Apr 1st, 2005 12:52 PM |