当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python File seek()用法及代码示例


文件 seek() 方法

seek() 方法是 Python 中的内置方法,用于设置当前文件位置(或文件指针)。

用法:

    file_object.seek(offset)

参数:

  • offset– 它指定设置当前文件位置的偏移量。

返回值:

这个方法的返回类型是<class 'int'>,它返回新的文件位置。

例:

# Python File seek() Method with Example

# creating a file 
myfile = open("hello.txt", "w")

# writing to the file
res = myfile.write("Hello friends, how are you?")
print(res, "bytes written to the file.")
# closing the file
myfile.close()

# reading content from the file
myfile = open("hello.txt", "r")
print("file content...")
print(myfile.read())

# sets the current file location to 6
print("file content from 6th position...")
myfile.seek(6)
print(myfile.read())

# sets the current file location to 0
print("file content from 0th position...")
myfile.seek(0)
print(myfile.read())

# sets the current file location to 12
print("file content from 12th position...")
myfile.seek(12)
print(myfile.read())

输出

27 bytes written to the file.
file content...
Hello friends, how are you?
file content from 6th position...friends, how are you?
file content from 0th position...
Hello friends, how are you?
file content from 12th position...
s, how are you?


相关用法


注:本文由纯净天空筛选整理自 Python File seek() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。