Python | os.lseek() method
Last Updated :
22 Nov, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.lseek()
method sets the current position of file descriptor fd to the given position pos which is modified by how.
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.
how: This is the reference point in the file. It also accepts three values which are
- os.SEEK_SET or 0 to set the reference point to the beginning of the file
- os.SEEK_CUR or 1 to set the reference point to the current position
- os.SEEK_END or 2 to set the reference point to the end of the file.
Return Value: This method does not returns any value.
Example #1 :
Using
os.lseek()
method to seek the file from beginning
import os
path = 'C:/Users/Rajnish/Desktop/testfile.txt'
fd = os. open (path, os.O_RDWR|os.O_CREAT)
s = 'GeeksforGeeks - A Computer Science portal'
line = str .encode(s)
os.write(fd, line)
os.lseek(fd, 0 , 0 )
s = os.read(fd, 13 )
print (s)
os.close(fd)
|
Output:
b'GeeksforGeeks'
Example #2 :
Using os.lseek()
method to to seek the file from specific position
import os
path = 'C:/Users/Rajnish/Desktop/testfile.txt'
fd = os. open (path, os.O_RDWR|os.O_CREAT)
s = 'GeeksforGeeks'
line = str .encode(s)
os.write(fd, line)
os.lseek(fd, 2 , 0 )
s = os.read(fd, 11 )
print (s)
os.close(fd)
|
Output:
b'eksforGeeks'
Share your thoughts in the comments
Please Login to comment...