Python os.lseek() Method
os.lseek() Overview
The os.lseek() method is used to set the current position of the file descriptor fd to pos, how way modified.
Valid in Unix, Windows.
os.lseek() Syntax
The lseek() method syntax format is as follows:
os.lseek(fd, pos, how)
os.lseek() Parameters
- fd — The file descriptor.
- pos — This is the position in the file relative to the given parameter how.
- how — The reference position within the file.
- os.SEEK_SET or 0 sets the pos to be calculated from the beginning of the file;
- os.SEEK_CUR or 1 calculates from the current position;
- os.SEEK_END or 2 starts at the end of the file.
os.lseek() Return Value
This method has no return value.
os.lseek() Demo#1
The following example demonstrates the use of the lseek() method:
# Python program to explain os.lseek() method
# importing os module
import os
# path
path = '/root/apidemos.com.txt'
# Open the file and get
# the file descriptor associated
# with it using os.open() method
fd = os.open(path, os.O_RDWR|os.O_CREAT)
# String to be written
s = 'ApiDemos.com - A website for api demos.'
# Convert the string to bytes
line = str.encode(s)
# Write the bytestring to the file
# associated with the file
# descriptor fd
os.write(fd, line)
# Seek the file from beginning
# using os.lseek() method
os.lseek(fd, 0, 0)
# Read the file
s = os.read(fd, 13)
# Print string
print(s)
# Close the file descriptor
os.close(fd)
Output:
os.lseek() Demo#2
Using os.lseek()
method to to seek the file from specific position
# Python program to explain os.lseek() method
# importing os module
import os
# path
path = '/root/apidemos.com.txt'
# Open the file and get
# the file descriptor associated
# with it using os.open() method
fd = os.open(path, os.O_RDWR|os.O_CREAT)
# String to be written
s = 'apidemos.com'
# Convert the string to bytes
line = str.encode(s)
# Write the bytestring to the fil
# associated with the file
# descriptor fd
os.write(fd, line)
# Seek the file after position '2'
# using os.lseek() method
os.lseek(fd, 2, 0)
# Read the file
s = os.read(fd, 11)
# Print string
print(s)
# Close the file descriptor
os.close(fd)
Output: