Python OS file/directory os.lseek() method

Python OS File/Directory os.lseek() Method

Description

The lseek() method sets the current position of the file descriptor fd to the given position pos, modified according to how.

Syntax

The following is the syntax of the lseek() method:

os.lseek(fd, pos, how)

Parameters

  • pos − This is the position in the file, relative to the given parameter how. You can use os.SEEK_SET or 0 to set the position relative to the beginning of the file, os.SEEK_CUR or 1 to set the position relative to the current position, and os.SEEK_END or 2 to set the position relative to the end of the file.
  • how − This is a reference point within the file. os.SEEK_SET or 0 represents the beginning of the file, os.SEEK_CUR or 1 represents the current position, and os.SEEK_END or 2 represents the end of the file.

The pos constant is defined.

  • os.SEEK_SET – 0
  • os.SEEK_CUR – 1

  • os.SEEK_END – 2

Return Value

This method does not return any value.

Example

The following example shows the use of the lseek() method.

import os, sys

#Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Write one string
line="This is test"
b=line.encode()
os.write(fd, b)

# Now you can use fsync() method.
# Infact here you would not be able to see its effect.
os.fsync(fd)

# Now read this file from the beginning
os.lseek(fd, 0, 0)
line = os.read(fd, 100)
print ("Read String is : ", line.decode())

# Close opened file
os.close(fd)
print ("Closed the file successfully!!")

When we run the above program it produces the following results –

Read String is : This is test
Closed the file successfully!!

Leave a Reply

Your email address will not be published. Required fields are marked *