文件 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 seekable()用法及代码示例
- Python File tell()用法及代码示例
- Python File flush()用法及代码示例
- Python File write()用法及代码示例
- Python File read()用法及代码示例
- Python File truncate()用法及代码示例
- Python File fileno()用法及代码示例
- Python File open()用法及代码示例
- Python File isatty()用法及代码示例
- Python File writable()用法及代码示例
- Python File writelines()用法及代码示例
- Python File readable()用法及代码示例
- Python File readlines()用法及代码示例
- Python File close()用法及代码示例
- Python File readline()用法及代码示例
- Python numpy.less()用法及代码示例
- Python Sympy Permutation.list()用法及代码示例
- Python Matplotlib.figure.Figure.subplots_adjust()用法及代码示例
- Python numpy.tril()用法及代码示例
- Python Matplotlib.pyplot.matshow()用法及代码示例
注:本文由纯净天空筛选整理自 Python File seek() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。