You can think of a file as a sequence of bytes (at least that is the case if you open up the file as a binary file using mode='rb'
), similar to a bytearray
stored on disk. When you first open the file with mode='rb'
, you are currently positioned or "pointing" at the beginning of the file, at offset 0, meaning that if you issue a read
for n
bytes you will be reading in the first n
bytes of the file (assuming the file has at least n
bytes worth of data). After the read your new file position is at offset n
. So if you do nothing but issue successive read
calls, you will read the file sequentially.
Method tell
returns your current "position", meaning simply your current offset within the file:
with open('myfile', 'rb') as f:
data = f.read(12) # after this read I should be at offset 12
print(f.tell()) # this should print out 12
Method seek
allows you to change your current position in the file:
import os
with open('myfile', 'rb') as f:
# read the last 12 bytes of the file:
f.seek(-12, os.SEEK_END) # seek 12 bytes before the end of the file
data = f.read(12) # after this read I should be at the end of the file
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…