當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python seek()用法及代碼示例

文件處理的概念用於保留程序運行後生成的數據或信息。與其他編程語言(如C,C++,Java,Python)一樣,它也支持文件處理。

Refer the below article to understand the basics of File Handling.

seek()方法

在Python中,seek()函數用於將文件句柄的位置更改為給定的特定位置。文件句柄就像一個遊標,它定義了必須從何處讀取或寫入文件中的數據。


用法:f.seek(offset, from_what), where f is file pointer

參數:
Offset:前進的位置數
from_what:它定義了參考點。

返回:不返回任何值

參考點由from_what參數選擇。它接受三個值:

  • 0:將參考點設置在文件的開頭
  • 1:將參考點設置在當前文件位置
  • 2:將參考點設置在文件末尾

默認情況下,from_what參數設置為0。

注意:除非偏移量等於0,否則無法在文本模式下設置當前位置/文件末尾的參考點。

範例1:假設我們必須讀取一個名為“GfG.txt”的文件,其中包含以下文本:

"Code is like humor. When you have to explain it, it’s bad."    
# Python program to demonstrate 
# seek() method 
  
  
# Opening "GfG.txt" text file 
f = open("GfG.txt", "r") 
  
# Second parameter is by default 0 
# sets Reference point to twentieth  
# index position from the beginning 
f.seek(20) 
  
# prints current postion 
print(f.tell()) 
  
print(f.readline())  
f.close()
輸出:
20
When you have to explain it, it’s bad.

範例2:具有負偏移量的Seek()函數僅在以二進製模式打開文件時才起作用。假設該二進製文件包含以下文本。

b'Code is like humor. When you have to explain it, its bad.'
# Python code to demonstrate  
# use of seek() function 
   
      
# Opening "GfG.txt" text file  
# in binary mode 
f = open("data.txt", "rb") 
  
# sets Reference point to tenth 
# position to the left from end 
f.seek(-10, 2) 
  
# prints current position 
print(f.tell()) 
  
# Converting binary to string and  
# printing 
print(f.readline().decode('utf-8')) 
  
f.close()
輸出:
47
, its bad.


相關用法


注:本文由純淨天空篩選整理自Soham_Lanke大神的英文原創作品 Python seek() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。