I'd like to start by saying that I'm very new to Python, and I started this project for fun.
Specifically, it’s simply a program which sends compliments to you as notifications periodically throughout the day. This is not for school, and I was actually just trying to make it for my girlfriend while introducing myself to Python.
With that in mind, here's my problem. I started this project by writing the simplest version of it: one you have to start each time your computer loads, and runs while you're actively using the computer. This portion works perfectly; however, I can't seem to figure out how to do the next step: have the program carry on as normal after reboot and save its progress.
I know how to get it to start up again after reboot. Still, I'm not sure how to save its progress. Particularly, since I'm pulling the compliments out of a text file, I'm not sure how to have the program save what line it's on before rebooting. This is needed as I don't want the program to start from the first compliment each time, as there are over 300 unique ones as of now.
In order to help you understand where my code currently is as for the best advice, I've shown it below:
import datetime
import time
from plyer import notification
Compliment = None
try:
with open('C:/Users/conno/Documents/compliments.txt') as f:
lines = f.readlines()
except:
print("I'm sorry, I can't give you a new compliment today because I can't find the file.")
for compliment in lines:
notification.notify(
title = "Your New Compliment for {}".format(datetime.date.today()),
message = compliment,
app_icon = "C:/Users/conno/Downloads/Paomedia-Small-N-Flat-Bell.ico",
timeout = 10
)
time.sleep(60*30)
I know I could easily have a variable count which line it is on, but how do I save that value?
You can simply save the count (which is the index of the last compliment line) as an integer in a pickle file, or easier in a text file and read from it every time your script starts after reboot.
import datetime
import time
from plyer import notification
Compliment = None
compliment_index = 0
try:
with open('C:/Users/conno/Documents/compliments.txt') as f:
lines = f.readlines()
except:
print("I'm sorry, I can't give you a new compliment today because I can't find the file.")
try:
with open('C:/Users/conno/Documents/compliments_counter.txt') as f:
compliment_index = int(f.readlines()[0])
except:
with open('C:/Users/conno/Documents/compliments_counter.txt', "w") as f:
f.write(str(compliment_index))
for index in range(compliment_index, len(lines)):
compliment = lines[index]
notification.notify(
title = "Your New Compliment for {}".format(datetime.date.today()),
message = compliment,
app_icon = "C:/Users/conno/Downloads/Paomedia-Small-N-Flat-Bell.ico",
timeout = 10)
with open('C:/Users/conno/Documents/compliments_counter.txt', "w") as f:
f.write(str(index))
time.sleep(60*30)
Well, you should save an index to a file or something before program shutting down.
Check this out: atexit — Exit handlers