简体   繁体   中英

How to write and read Python var from file

I am building a CNC machine controlled by a python script. When the script finishes I want it to write its current location in x and y axis to a file, so that when the script is run again, it can read the var and know it current location and be able to return to start position.

I have been looking at configParser, but it seems over the top for what I need.

What would be the best way to do this?

I don't know in which way you store your positions. Below is a code sample that stores the two floating point values in a text file separated by a space and reads them again to a list object. In comments is the version with the values stored as single variables. If this is the best way I don't know.

#!/usr/bin/env python

#x=1.123
#y=2.123

pos = [1.123, 2.123]

with open('vars.txt','w') as f:
    f.write("%s %s" % (pos[0], pos[1]))
    #f.write("%s %s" % (x,y))

with open ('vars.txt', 'r') as myfile:
    position=myfile.read().split()

position = map(float, position)
# position = [1.123, 2.123]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM