Python | os.lseek () method

Python Methods and Functions

os.lseek () sets the current position of the file descriptor fd to the given position pos, which is modified in the how way.

  Syntax:  os.lseek (fd, pos, how)  Parameters:   fd:  This is the file descriptor on which seek is to be performed.  pos:  This is the position in the file with respect to given parameter  how . It can accept three values ​​which are 
  • 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
  • os.SEEK_END or 2, to set the position relative to the end of the file.

as: is a breakpoint in the file. It also takes three values, which

  • os.SEEK_SET or 0, to set a breakpoint at the beginning of the file
  • os.SEEK_CUR or 1, to set the checkpoint to the current position
  • os.SEEK_END or 2 , to set the anchor point to the end of the file.

Returned value: This method does not return any value.  Example # 1: Using os.lseek () to find a file from the beginning

# Python program to explain the os.lseek () method

 
# import of the os module

import os 

 
# path

path = 'C: / Users / Rajnish /Desktop/testfile.txt'

 
# Open the file and get
# the file descriptor associated
# using the os.open () method

fd = os. < / code> open (path, os.O_RDWR | os.O_CREAT)

 
# Line to write

s = 'Python.Engineering - A Computer Science portal'

  
# Convert string to bytes

line = str . encode (s)

 
# Write line to file
# associated with file
# fd descriptor
os.write (fd, line)

 
# Search file from beginning
 # using the os.lseek () method

os.lseek (fd, 0 , 0 )

 
# Read file

s = os.read (fd, 13 )

 
# Print line

print (s)

 
# Close the file descriptor
os.close (fd)

Exit :

 b'GeeksforGeeks' 

Example # 2:

Using os.lseek () to find a file from a specific position ui

# Python program to explain the os.lseek () method

 
# import of the os module

import os 

  
# path

path =   'C: / Users / Rajnish / Desktop / testfile.txt'

 
# Open the file and get
# file descriptor associated
# using os.open () method

fd = os. open (path, os. O_RDWR | os.O_CREAT)

 
# Write string

s = 'GeeksforGeeks'

 
# Convert string to bytes

line = str . encode (s)

 
# Write line to file
# associated with the file
# descriptor fd
os.write (fd, line)

 

 
# Search for file after position & # 39; 2 & # 39;
# using the os.lseek () method

os.lseek (fd, 2 , 0 )

 
# Read file

s = os.read (fd, 11 )

 
# Print line

print (s)

 
# Close the file descriptor
os.close (fd)

Exit :

 b'eksforGeeks'