Python os.lseek() 方法



lseek() 方法是 Python OS 模組的一個函式。它用於設定檔案描述符相對於給定位置的當前位置。

在 Python 中,每個開啟的檔案都與一個檔案描述符相關聯。os.lseek() 方法可以將此檔案描述符的指標移動到特定位置,以進行讀取和寫入操作。

語法

以下是 Python lseek() 方法的語法 -

os.lseek(fd, pos, how)

引數

Python lseek() 方法接受以下引數 -

  • fd - 這是需要處理的檔案描述符。
  • pos - 它指定檔案中相對於給定引數“how”的位置。您可以使用 os.SEEK_SET 或 0 來設定相對於檔案開頭的相對位置,使用 os.SEEK_CUR 或 1 來設定相對於當前位置的相對位置;使用 os.SEEK_END 或 2 來設定相對於檔案末尾的相對位置。
  • how - 這是檔案中的參考點。os.SEEK_SET 或 0 表示檔案開頭,os.SEEK_CUR 或 1 表示當前位置,os.SEEK_END 或 2 表示檔案末尾。

返回值

Python lseek() 方法不返回值。

示例

以下示例顯示了 lseek() 方法的使用方法。這裡,我們從開頭讀取給定檔案到接下來的 100 個位元組。

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!!")

當我們執行上面的程式時,它會產生以下結果 -

File contains the following string: b'This is test.'
Closed the file successfully!!

示例

在以下示例中,我們將檔案指標移動到特定位置。當我們讀取檔案時,指標將從指定位置開始。

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!!")

執行上述程式後,它將顯示以下結果 -

Reading the file content:
b' to the file'
File Closed Successfully!!
python_files_io.htm
廣告