python - How do I fix this speed varible writing back to file? -
i've been writing program, i've run error. current code is:
import tkinter tk speed = 80 def onkeypress(event, value): global speed text.delete("%s-1c" % 'insert', 'insert') text.insert('end', 'current speed: %s\n\n' % (speed, )) open("speed.txt", "r+") p: speed = p.read() speed = int(speed) speed = min(max(speed+value, 0), 100) open("speed.txt", "r+") p: p.writelines(str(speed)) print(speed) if speed == 100: text.insert('end', 'you have reached speed limit') if speed == 0: text.insert('end', 'you can not go slower') speed = 80 root = tk.tk() root.geometry('300x200') text = tk.text(root, background='black', foreground='white', font=('comic sans ms', 12)) text.pack() # individual key bindings root.bind('<keypress-w>', lambda e: onkeypress(e, 1)) root.bind('<keypress-s>', lambda e: onkeypress(e, -1)) # root.mainloop()
i believe speed = min(...)
causing error. guys have idea?
one problem (i guess it's problem you're having) trying overwrite content of file speed.txt
, however, value writing contains fewer characters contained in file.
this can lead unexpected values winding in file, e.g. if file contains
10
consider happens if try decrement value 1 (user hit s
key):
with open('speed.txt', 'r+') p: speed = int(p.read()) speed -= 1 # speed 9 open("speed.txt", "r+") p: p.writelines(str(speed))
speed.txt
contains:
90
instead of decreasing speed 9, has been increased 90! if speed 100 , tried decrement it, end 990 in file.
this because opening file mode r+
opens file reading , writing , positions file pointer @ beginning of file. write overwrite first n characters n length of data written. hence can sort of corruption shown above.
you can fix opening file mode 'w'
_second__ open()
. overwrite file. , don't need use writelines()
, use write()
.
Comments
Post a Comment