From 5aa4f65c9f205c45af77cea44a9a48cd10676e42 Mon Sep 17 00:00:00 2001 From: Ruben Date: Thu, 4 Jan 2018 21:18:32 +0100 Subject: [PATCH] Fix file read error --- scan_faces.py | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/scan_faces.py b/scan_faces.py index e154fb2..c8ded7f 100755 --- a/scan_faces.py +++ b/scan_faces.py @@ -54,22 +54,36 @@ lcd.message("Init scanner...") prevFaceCount = 0 totalUse = 0 #in face-seconds +logfile = "/home/pi/scan_faces/scan_faces.log" + +def tail(filepath): + """ + Thanks: https://stackoverflow.com/a/41491521 + """ + with open(filepath, "rb") as f: + first = f.readline() # Read the first line. + f.seek(-2, 2) # Jump to the second last byte. + while f.read(1) != b"\n": # Until EOL is found... + try: + f.seek(-2, 1) # ...jump back the read byte plus one more. + except IOError: + f.seek(-1, 1) + if f.tell() == 0: + break + last = f.readline() # Read last line. + return last + # make sure log file exists -if not os.path.exists("scan_face.log") - with open("scan_face.log","w") as f: +if not os.path.exists(logfile): + with open(logfile,"w") as f: f.write("{},{},{}".format(time.time(), 0,0)) # get last line of log file and update 'total use' using that. -with open("scan_face.log", "rb") as f: - first = f.readline() # Read the first line. - f.seek(-2, os.SEEK_END) # Jump to the second last byte. - while f.read(1) != b"\n": # Until EOL is found... - f.seek(-2, os.SEEK_CUR) # ...jump back the read byte plus one more. - last = f.readline() # Read last line. - bits = last.split(",") - totalUse = bits[2] +last = tail("") +bits = last.split(",") +totalUse = bits[2] -log = open("scan_face.log", "a") +log = open(logfile, "a") lastFaceTime = datetime.datetime.utcnow()