[Tutor] Working with files, Truckers log

Alexandre Ratti alex@gabuzomeu.net
Fri, 05 Apr 2002 19:28:55 +0200


Hello,


At 03:38 05/04/2002 -0500, you wrote:
>Subject: Re: [Tutor] Working with files, Truckers log
>From: glidedon <glidedon@c-zone.net>
>Date: Thu, 04 Apr 2002 17:58:03 +0000

>This is a timely subject for me :-). I want to save data that is in a list
>to a file , to be  used later to append the list.  The list contains decimal
>numbers.
>
>Here is a sample list [ 8.5,8,9.5,10.75,6.25 ]
>
>I think I know how to read and write to a file ,but how do I insert this data
>into the list in my program ?

If you store your values in a text file, for instance one per line, it will 
be fairly simple to load them back and append them to a list. You can use 
eval() to transform a string value into a decimal value.

Note that eval() is often considered a security risk since it will happily 
execute any code. Is is advisable to test any input string before feeding 
it to eval() to make sure it only contains safe data.

Here is a function I used a couple of days ago:

import re

def isNumeric(inputString):
     "Returns TRUE is inputString only contains digits (or a dot)."
     expr = re.compile("^[\d\.]+$")
     return not(expr.search(inputString) == None)

Usage example:

if isNumeric(inputString):
     value = eval(inputString)
else:
     raise "Funny value error!"

(snip)

>while 1:
>     add_days = raw_input('\n' 'Do you want to add more days to recap 
> ?  y/n
>: ' )
>
>     if add_days in ( 'y','Y', 'yes','YES', 'ok', 'OK', 'yeah', 'YEAH' ) :

You may want to lowercase the input string add_day before testing it so 
that you can support different answers more easily (you would not need to 
store both "y" and "Y" in the response list).


Cheers.

Alexandre