Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。
os.lseek()
方法將文件描述符fd的當前位置設置為給定位置pos,該位置可以通過方式修改。
用法: os.lseek(fd, pos, how) 參數: 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
- 操作係統SEEK_SET或0設置相對於文件開頭的位置
- 操作係統SEEK_CUR或1設置相對於當前位置的位置
- 操作係統SEEK_END或2設置相對於文件末尾的位置。
- 操作係統SEEK_SET或0將參考點設置為文件的開頭
- 操作係統SEEK_CUR或1將參考點設置為當前位置
- 操作係統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'
相關用法
- Python next()用法及代碼示例
- Python os.dup()用法及代碼示例
- Python set()用法及代碼示例
- Python Decimal max()用法及代碼示例
- Python PIL ImageOps.fit()用法及代碼示例
- Python os.rmdir()用法及代碼示例
- Python sympy.det()用法及代碼示例
- Python Decimal min()用法及代碼示例
- Python os.readlink()用法及代碼示例
- Python os.writev()用法及代碼示例
- Python os.readv()用法及代碼示例
- Python PIL RankFilter()用法及代碼示例
- Python os.rename()用法及代碼示例
- Python os.sendfile()用法及代碼示例
注:本文由純淨天空篩選整理自Rajnis09大神的英文原創作品 Python | os.lseek() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。