[Tutor] Fwd: Re: Using files to read data
Mats Wichmann
mats at wichmann.us
Tue Jun 27 12:13:42 EDT 2017
On 06/27/2017 05:01 AM, Alan Gauld via Tutor wrote:
> Forwarding to list
>
> Please always use ReplyAll or ReplyList when responding to list mail.
>
>
>
> -------- Forwarded Message --------
>
> i apologize. i guess it didn’t attach correctly.
> my issue is how do i get it out of my file and use it.
>
> *the json file, its only about a fifth of it but it should serve its
> purpose*
> [
> 0.9888888888888889,
> 0.011111111111111112,
> "Mon Jun 26 20:37:34 2017"
> ]
A few thoughts here...
suggest storing the time not as a datetime string, but as a time value.
That is, use time.time() to generate it; you can always convert that
value to a string later if needed.
if you're going to write as json, then you should read as json, don't
create your own reader.
in order to get data serialized in a more usable form, you could define
a class, and serialize the class instances, this way you get the
variable name stored along with the data. Since json only understands a
limited number of data types, one cheap approach is to fish out the
dictionary of data from the instance object - json does understand
dicts. I'm using vars() for that. So here's a cheap example, not
fleshed out to use any of your code:
import time
import json
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.time = time.time()
# create a few points
A = Point(0.022222222222222223, 0.9777777777777777)
B = Point(0.011111111111111112, 0.9888888888888889)
print(json.dumps(vars(A)))
print(json.dumps(vars(B)))
You'll see you get formatted data that json.loads() ought to be able to
make use of:
{"y": 0.9777777777777777, "x": 0.022222222222222223, "time":
1498577730.524801}
{"y": 0.9888888888888889, "x": 0.011111111111111112, "time":
1498577730.524802}
You don't need a class for that, you can just build the dict yourself,
it was just a cheap way to illustrate.
Simulated read:
>>> import json
>>> point = json.loads('{"y": 0.9777777777777777, "x":
0.022222222222222223, "time": 1498577980.382325}')
>>> print(point['x'])
0.0222222222222
>>> print(point['y'])
0.977777777778
>>> print(point(['time'])
1498577980.38
>>>
I wouldn't open/close the json file you're writing to each time, that
seems a bit wasteful.
And do take on board some of the refactoring suggestions already made.
Dividing the heading by 90 using integer division (//) will give you
four possible values, 0-3, you can then base your definitions/decisions
on that, instead of your "if heading in range(1, 91):" selections.
range actually generates the values, which you don't really need.
Best of luck!
More information about the Tutor
mailing list