Writing and reading variables to/from flat file

Jonathan Curran jonc at icicled.net
Fri Dec 15 01:17:12 EST 2006


On Thursday 14 December 2006 09:31, Kevin Walzer wrote:
> I want to write some variables (user preferences, specifically) to a
> text file and then read the values from that file.
>
> Here is my code to write the data:
>
> verbosemodes= """
>     Detailed = "-vv"
>     Basic = "-q"
>     """
>
> file = open('prefs', 'w')
>
> file.writelines(verbosemodes)
>
> file.close()
>
> And here is my code, in a separate module, to read the file and display
> the variable values:
>
> readfile = open('prefs').readlines()
>
> for line in readfile:
> 	print line
>
> print Basic
>
>
> Running the second module yields this error:
>
>     Detailed = "-vv"
>
>     Basic = "-q"
>
>
> Traceback (most recent call last):
>   File "readprefs.py", line 6, in <module>
>     print Basic
> NameError: name 'Basic' is not defined
>
> Clearly the data is getting read (the lines are being printed), but the
> variable itself ("Basic") is not being initialized properly. I'm not
> sure what I'm doing wrong here--can anyone point me in the right
> direction?  Thanks.
>
> --
> Kevin Walzer
> Code by Kevin
> http://www.codebykevin.com

I'm surprised that no one has mentioned the wonderful ConfigParser class. 
Documentation is @ http://docs.python.org/lib/module-ConfigParser.html

Straight to the point example @ 
http://mail.python.org/pipermail/tutor/2001-November/010066.html

This way you can focus on your application instead of dealing with trivial 
things such as saving/loading data :)

- Jonathan Curran



More information about the Python-list mailing list