python seek使用_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.
總結
以上是生活随笔為你收集整理的python seek使用_Python seek()用法及代码示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: K12在线教育发展前景分析
- 下一篇: websocket python爬虫_p