Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

file - (Python 3) I have some questions regarding seek() and tell()

I am currently learning Python 3 with the Zed Shaw's book, Learning Python 3 The Hard Way.

When doing exercise 20 about functions and files, you get tasked with researcher what does the seek function does. By searching online I've come across with a couple of concepts regarding this function that I'm having trouble getting my head around:

Here's an explanation I've found online about seek()'s purpose:

Python file method seek() sets the file's current position at the offset.

  • Under this context, what would "The file's current position" mean?

Here's an explanation I've found online about tell()'s purpose:

Python file method tell() returns the current position of the file read/write pointer within the file.

  • Under this context, what would "The file read/write pointer" mean?
question from:https://stackoverflow.com/questions/65540645/python-3-i-have-some-questions-regarding-seek-and-tell

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...