Python| os.lseek() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。
os.lseek()
方法将文件描述符fd的当前位置设置为由how修改的给定位置 pos。
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或0设置相对于文件开头的位置
- os.SEEK_CUR或1设置相对于当前位置的位置
- os.SEEK_END或2设置相对于文件末尾的位置。
- os.SEEK_SET或0将参考点设置为文件的开头
- os.SEEK_CUR或1将参考点设置为当前位置
- os.SEEK_END或2将参考点设置为文件末尾。
os.lseek()
方法从头开始寻找文件# Python program to explain os.lseek() method
# importing os module
import os
# path
path = 'C:/Users/Rajnish/Desktop/testfile.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 = 'GeeksforGeeks - A Computer Science portal'
# 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)
输出:
b'GeeksforGeeks'
示例 #2:
使用os.lseek()
方法从特定位置查找文件
# Python program to explain os.lseek() method
# importing os module
import os
# path
path = 'C:/Users/Rajnish/Desktop/testfile.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 = 'GeeksforGeeks'
# 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 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)
输出:
b'eksforGeeks'
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。