Python seek end of file

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.



Description

Python file method seek() sets the file's current position at the offset. The whence argument is optional and defaults to 0, which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.

There is no return value. Note that if the file is opened for appending using either 'a' or 'a+', any seek() operations will be undone at the next write.

If the file is only opened for writing in append mode using 'a', this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode 'a+').

If the file is opened in text mode using 't', only offsets returned by tell() are legal. Use of other offsets causes undefined behavior.

Note that not all file objects are seekable.

Syntax

Following is the syntax for seek() method −

fileObject.seek(offset[, whence])

Parameters

  • offset − This is the position of the read/write pointer within the file.

  • whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.

Return Value

This method does not return any value.

Example

The following example shows the usage of seek() method.

Python is a great language
Python is a great language
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

line = fo.readline()
print "Read Line: %s" % (line)

# Again set the pointer to the beginning
fo.seek(0, 0)
line = fo.readline()
print "Read Line: %s" % (line)

# Close opend file
fo.close()

When we run above program, it produces following result −

Name of the file:  foo.txt
Read Line: Python is a great language.

Read Line: Python is a great language.

python_files_io.htm

When we open a file for reading with Python (thought this is true for any programming lanuage), we get a filehandle that points to the beginning of the file. As we read from the file the pointer always points to the place where we ended the reading and the next read will start from there.

That is, unless we tell the filehandle to move around.

The tell method of the filehandle will return the current location of this pointer.

The seek method will move the pointer.

In this example first we create a file and then open it and fool around with tell and seek for no particular reason just to show how they work.

examples/python/seek.py

import os

filename = '/tmp/data.txt'
with open(filename, 'w') as fh:
    fh.write("Hello World!\nHow are you today?\nThank you!")

print(os.path.getsize(filename))  # 42

with open(filename) as fh:
    print(fh.tell())        # 0
    row = fh.readline()
    print(row)              # Hello World!
    print(fh.tell())        # 13

    fh.seek(-7, os.SEEK_CUR)
    print(fh.tell())        # 6

    row = fh.readline()
    print(row)              # World!
    print(fh.tell())        # 13

    fh.seek(0, os.SEEK_SET)
    print(fh.tell())        # 0
    print(fh.read(5))       # Hello

    fh.seek(-4, os.SEEK_END)
    print(fh.tell())        # 38
    print(fh.read())        # you!
    print(fh.tell())        # 42

seek gets two parameters. The first says how many bytes to move (+ or -) the second parameter tells it where to start from. In some cases the former is called offset and the latter is called whence.

The whence can be any of the following values:

  • os.SEEK_SET - beginning of the file
  • os.SEEK_CUR - current position
  • os.SEEK_END - end of file

A positive offset will move the pointer forward, a negative offset would move backward.

Special cases

There are two special cases:

fh.seek(0, os.SEEK_SET)  - go to the beginning of the file.
fh.seek(0, os.SEEK_END)  - go to the end of the file.

How do you get to the end of a file in Python?

Python doesn't have built-in eof detection function but that functionality is available in two ways: f. read(1) will return b'' if there are no more bytes to read. This works for text as well as binary files. The second way is to use f.

What does seek () do in Python?

In Python, seek() function is used to change the position of the File Handle to a given specific position..
0: sets the reference point at the beginning of the file..
1: sets the reference point at the current file position..
2: sets the reference point at the end of the file..

What is the use of SEEK () in files?

The seek() method sets the current file position in a file stream.

How do you move the cursor to the end of a file in Python?

Set whence to 2 and the offset to 0 to move the file pointer to the end of the file.