Writing and reading variables to/from flat file

Caleb Hattingh caleb.hattingh at gmail.com
Fri Dec 15 04:10:53 EST 2006


Hi Kevin

The other posters helped you with configParser, which is what you
wanted, i.e. text file access.

However, you can also get persistance really cheaply with pickling, if
you don't need the saved data to be text-editable:

(from memory)

verboseSettings = {}
verboseSettings['Detailed'] = '-vv'
verboseSettings['Basic'] = '-q'

import cPickle
# Save the data - Just give the dict!
cPickle.dump(verboseSettings, file('prefs','w+'))

# Load the data back - get the dict back
verboseSettings = cPickle.load(file('prefs','r'))

I recently did a ton of scientific data analysis looking for trends in
10 years of data for a petrochemical plant, and I learned just how
convenient dicts and pickles can be to manage one's sanity :)

Caleb

On Dec 14, 4:31 pm, Kevin Walzer <k... at codebykevin.com> 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 Kevinhttp://www.codebykevin.com




More information about the Python-list mailing list