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.
SyntaxFollowing is the syntax for Python lseek() method −
os.lseek(fd, pos, how)Parameters
The Python lseek() method accepts the following parameters −
The Python lseek() method does not return any value.
ExampleThe 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4