Python3 os.lseek() Method

Python3 OS File/Directory Methods


Overview

The os.lseek() method is used to set the current position of file descriptor fd to pos, with the how parameter specifying how it is modified.

Valid in Unix and Windows.

Syntax

lseek()The method syntax is as follows:

os.lseek(fd, pos, how)

Parameters

  • fd-- File descriptor.

  • pos-- This is the position in the file relative to the given argument how.

  • how-- Reference position within the file. SEEK_SET or 0 sets pos calculated from the beginning of the file; SEEK_CUR or 1 calculates from the current position; os.SEEK_END or 2 starts from the end of the file.

Return Value

This method has no return value.

Example

The following example demonstrates the use of the lseek() method:

#!/usr/bin/python3

import os, sys

# 打开文件
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# 写入字符串
os.write(fd, "This is test")

# 所有 fsync() 方法
os.fsync(fd)

# 从开始位置读取字符串
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("Read String is : ", str)

# 关闭文件
os.close( fd )

print ("关闭文件成功!!")

The output of the above program is:

File closed successfully!!

Python3 OS File/Directory Methods

Other Extensions