[Tutor] Reading numbers from a text file

Phil phil_lor at bigpond.com
Wed Jul 10 10:41:22 CEST 2013


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]


Maybe I would be better off continuing with pickle?

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"))


nums = pickle.load(open("save_num", "rb"))
print(nums[0])
print(nums[1])

-- 
Regards,
Phil


More information about the Tutor mailing list