Editing File

Maric Michaud maric at aristote.info
Wed Jul 12 12:14:32 EDT 2006


Le mercredi 12 juillet 2006 17:00, D a écrit :
> Thanks, guys.  So overall, would it just be easier (and not too rigged)
> if any changes were made by just editing the text file?  I want to do
> this project the right way, but if it's going to be a big pain to
> implement the edit function, just modifying the text file directly
> isn't that big of a deal..

If you don't want to rely on third party libraries, and want a human-readable 
format I'll suggest using csv file format :

and this way ?

In [47]: class Z(object) :
   ....:     def __init__(self, val) : self.val = val
   ....:
   ....:

In [48]: lst = [Z(i) for i in range(2) + [ str(e) for e in range(2) ] ]

In [49]: [ (e, e.val) for e in lst ]
Out[49]:
[(<__main__.Z object at 0xa76c252c>, 0),
 (<__main__.Z object at 0xa76c27ac>, 1),
 (<__main__.Z object at 0xa76c23ac>, '0'),
 (<__main__.Z object at 0xa76c23ec>, '1')]

In [51]: csv.writer(file('config.csv', 'w')).writerows([ 
(type(i.val).__name__, i.val) for i in lst])

In [52]: print file('config.csv').read()
int,0
int,1
str,0
str,1


In [53]: l = [ Z(eval(class_)(val)) for class_, val in 
csv.reader(file('config.csv')) ]

In [54]: [ (e, e.val) for e in l ]
Out[54]:
[(<__main__.Z object at 0xa76c218c>, 0),
 (<__main__.Z object at 0xa76c260c>, 1),
 (<__main__.Z object at 0xa76c256c>, '0'),
 (<__main__.Z object at 0xa76c25cc>, '1')]




-- 
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097



More information about the Python-list mailing list