日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python seek使用_Python seek()用法及代码示例

發布時間:2023/12/20 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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()用法及代码示例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。