[Tutor] Reading numbers from a text file

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Jul 10 12:25:15 CEST 2013


On 10 July 2013 09:41, Phil <phil_lor at bigpond.com> wrote:
> Thank you for reading this.
>
> Kububtu 13.04 Python 3
>
> I'm attempting to read a configuration file that will restore my program to
> the state that it was in when it was closed. Ideally the config file would
> be human readable.
>
> For this example I want to save and then read back the variables x and y.
> The variables are written to the file correctly.
>
> with open("config_file", "w") as file:
>     x = 12
>     y = 67
>     file.write("%d %d\n" % (x, y))
>
>
> This is my best attempt at reading back the variables. As it stands, myvars
> = "12". If I change "[0]" to "[1]" then, of course I have the second
> variable. How do I over come this seemingly simple problem?
>
> with open("config_file", "r") as file:
>     myvars = file.read().splitlines()
>
>     myvars = [i.split(" ")[0] for i in myvars]

If you just remove the "[0]" from the line above then i.split(" ")
will return a list of both x and y. Then you can do e.g.:

x, y = myvars[0]

> Maybe I would be better off continuing with pickle?

That depends how complicated your data really is. Another possibility
is json e.g.:

>>> x = 1
>>> y = 2
>>> variables = {'x': x, 'y': y}
>>> variables
{'y': 2, 'x': 1}
>>> import json
>>> json.dumps(variables, indent=4)
'{\n    "y": 2, \n    "x": 1\n}'
>>> print(json.dumps(variables, indent=4))
{
    "y": 2,
    "x": 1
}
>>> stringdata = json.dumps(variables, indent=4)
>>> json.loads(stringdata)
{u'y': 2, u'x': 1}

That's relatively readable and works for simple data.

>
> This works perfectly except the file is in a binary format and, although I
> haven't spent a lot of time on it, I haven't managed to get it working in a
> text format.
>
> import pickle
> numbers = [12,98]
> pickle.dump(numbers, open("save_num", "wb"))

Instead of the above you should use:

with open('save_num', 'wb') as savefile:
    pickle.dump(numbers, savefile)

This ensures that the file is closed properly and that all the data
gets written.


Oscar


More information about the Tutor mailing list