The first error is that datetime.date.today
does not exist as you are importing. Most importantly, do not mind using wildcard ( *
) never except for a handful of cases where it's justified, it's a bad practice. It reduces the legibility of the code (favoring errors like this among other things), populates the main namespace without any need and can cause conflicts with identifiers of the main namespace causing its masking and the consequent errors, sometimes silent.
If you import using import datetime
you can call the method today
of the class date
of the module datetime
without problems using datetime.date.today()
. If you import how you do (not recommended) or by from datetime import date
it should be date.today()
.
On the other hand, datetime.date.today
returns an object datetime.date
not a chain, you can not do f.write(today)
directly, in any case you must make an explicit casting before str
.
On the other hand, I do not know very well what you expect with the variable alreadyStored
, it's a local variable but you do not use it at any time for anything in the function, apart from assigning value to it. If it is a global variable, as you do it you will not modify it globally (the change is not reflected outside the function), you must indicate that it is treated as global before assigning it the value within the function with global alreadyStored
. As you do, even if the variable is defined globally, assigning a value creates a new local variable with the same name and the global variable is not modified. It generally avoids the use of global variables, it is better that the function returns True
or False
than having it modify a global variable, common source of errors and loss of code readability.
Without considering alreadyStored
given that I do not know what function it has in your code, everything could look like this:
import datetime
def check_if_saving():
today = str(datetime.date.today())
with open("checktime.txt", "r+") as f:
last_date = f.read()
if last_date != today:
f.seek(0)
f.write(today)
f.truncate()
addMoney()
Only the file is opened once and the context manager is used via with
which is responsible for closing the file automatically when the execution of its code block ends.
I recommend looking at the style conventions of the Python code defined in PEP-8, the readability of the code is a very important aspect in Python: