How to .seek() end of .txt file with Python 3.5
Solution 1
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()
.
Solution 2
Your parameters to seek
are incorrect, seek
takes 2 parameters, an offset (how many bytes) and whence which describes from where to seek (start:0, current:1, end:2). So what you need is:
import io
sessionRecord.seek(0, io.SEEK_END)
Or:
sessionRecord.seek(0, 2) # Py2
But you can avoid doing this by opening the file in append mode:
with open('<filename>', 'a'):
sessionRecord.write(...)
Aanand Kainth
BY DAY: Regular Teenager BY NIGHT: HEAVYWEIGHT SLEEPER
Updated on July 16, 2020Comments
-
Aanand Kainth almost 4 years
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.
-
jasonharper almost 4 yearsYou aren't closing your file after writing to them, so if you look at the file while the program is still running, you may see incomplete data because some data is likely still in a buffer, and not physically written to the disk yet.
-
-
Aanand Kainth over 8 yearsWait, so what would that do? Doesn't that just put me in the second row?
-
AChampion over 8 yearsIt seeks to the end of the file.
-
Aanand Kainth over 8 yearsThanks! Because this was posted first, and it worked, I will mark this as the accepted answer.