Python os.lseek() Method



The lseek() method is a function of Python OS module. It is used to set the current position of file descriptor with respect to the given position.

In Python, every open file is associated with a file descriptor. The os.lseek() method can move the pointer of this file descriptor to a specific location for reading and writing purposes.

Syntax

Following is the syntax for Python lseek() method −

os.lseek(fd, pos, how)

Parameters

The Python lseek() method accepts the following parameters −

  • fd − This is the file descriptor, which needs to be processed.
  • pos − It specifies the position in the file with respect to given parameter "how". You give os.SEEK_SET or 0 to set the position relative to the beginning of the file, os.SEEK_CUR or 1 to set it relative to the current position; os.SEEK_END or 2 to set it relative to the end of the file.
  • how − This is the reference point within the file. os.SEEK_SET or 0 means beginning of the file, os.SEEK_CUR or 1 means the current position and os.SEEK_END or 2 means end of the file.

Return Value

The Python lseek() method does not return any value.

Example

The following example shows the usage of lseek() method. Here, we are reading the given file from beginning till the next 100 bytes.

import os, sys

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

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

# Now you can use fsync() method.
os.fsync(fd)

# Now read this file from the beginning
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("File contains the following string:", str)

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

When we run above program, it produces following result −

File contains the following string: b'This is test.'
Closed the file successfully!!

Example

In the following example, we are moving the file pointer to a specific position. When we will read the file the pointer will start from the specified position.

import os

# Open a file and create a file descriptor
fd = os.open("exp.txt", os.O_RDWR|os.O_CREAT)

# Write a string to the file
os.write(fd, b"Writing to the file")

# Moving the file pointer to specific position
os.lseek(fd, 7, os.SEEK_SET)

# Reading the file from specified position
print("Reading the file content:")
content = os.read(fd, 100)
print(content)  

# Closing the file
os.close(fd)
print ("File Closed Successfully!!")

On executing the above program, it will display the following result −

Reading the file content:
b' to the file'
File Closed Successfully!!
python_files_io.htm
Advertisements