文件 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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。