I am making a program that records what a user does in a user friendly Log File, which is stored as a .txt. So far, it just records the beginning of the session and the end, which is the exact same time. However, currently when I run the program, it removes the prior content of the file. I believe it is due to the fact that the cursor is seeking to point (0, 0). Is there a way to get to the end of the file? The code is as follows.
import atexit
import datetime
def logSession():
sessionRecord = open(r'C:\Users\Aanand Kainth\Desktop\Python Files\Login Program\SessionRecords.txt', "r+")
sessionRecord.seek(-1,-1)
sessionRecord.write("Session Began: " '{:%Y-%m-%d | %H:%M:%S}'.format(datetime.datetime.now()) + "\n")
def runOnQuit():
sessionRecord = open(r'C:\Users\Aanand Kainth\Desktop\Python Files\Login Program\SessionRecords.txt', "r+")
sessionRecord.seek(-1,-1)
sessionRecord.write("Session Ended: " '{:%Y-%m-%d | %H:%M:%S}'.format(datetime.datetime.now()) + """\n-------------------------------------------------------------------------------------------\n""")
logSession()
atexit.register(runOnQuit)
If you create the necessary files on your computer, and run this .PY file, you will find that sometimes it works as desired, and other times it doesn't. Can anyone tell me how to seek to the end, or if there is a better solution to help me? This is a self-assigned challenge, so I don't appreciate giveaways, and just hints.
Just open the file in the proper mode. If you want to add to a file without deleting its previous contents, use 'a'
(for "append") instead of 'r+'
, which is a truncating read/write. You will then no longer need to use seek()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With