Python | os.lseek 函数

最近更新时间 2020-12-10 11:24:11

os.lseek 函数将文件描述符 fd 的当前位置设置为 pos,参数 how 为位置计算方式,如下所示:设置为 SEEK_SET 或 0 表示从文件开始计算,设置为 SEEK_CUR 或 1 表示从文件当前位置计算,设置为 SEEK_END 或 2 表示文件末尾计算。返回新指针位置,这个位置是从文件开头计算的,单位是字节。

某些操作系统可能支持其他值,例如 os.SEEK_HOLE 或 os.SEEK_DATA。

函数定义

os.lseek(fd, pos, how)
# 函数定义

def lseek(fd: int, pos: int, how: int) -> int: ...

参数

  • checkfd - 文件描述符。
  • checkpos - 设置的文件位置。
  • checkhow - 位置计算方式。
    • os.SEEK_SET=0 从文件开始位置计算。
    • os.SEEK_CUR=1 从文件当前位置计算。
    • os.SEEK_END=2 从文件文件末尾计算。

返回值

  • checkint - 位置。

示例1: - 使用 os.lseek() 函数设置文件的位置。

# coding=utf-8

# Python3 代码
# 讲解怎样使用 os.lseek() 函数设置文件的位置

# 引入 os 库
import os

# 文件路径
path = "foo.txt"

# 使用 os.open 函数获取文件描述符
fd = os.open(path, os.O_RDWR)

# 使用 os.lseek() 设置文件的位置
pos = os.lseek(fd, 2, os.SEEK_CUR)
print("lseek::", pos)

# 关闭文件
os.close(fd)
lseek:: 2
rss_feed