Python Tutorial - Seek and Tell Functions

Python Exercise Lists

Before explaining the seek function and tell function, let's first understand what a file pointer is.

We know that when you use the open function to open a file and read the contents of the file, it always starts with the first character (byte) of the file. So, is there a way to specify the starting position for reading? The answer is yes, this requires moving the position of the file pointer.

The file pointer is used to indicate the starting position of the file reading and writing. If the file is viewed as a stream, each data in the file (opened in b mode, each data is a byte; opened in normal mode, each data is a character) is equivalent to a water drop, and the file pointer is marked “This is where the file will start to read”.

It can be seen that by moving the position of the file pointer and then using the read and write functions, it can be easily implemented to read the data at the specified position in the file (or write data to the specified position in the file).

Note that when writing data to a file, if it is not the end of the file, the original data at the writing position will not move backwards by itself, and the newly written data will directly overwrite the data at that position in the file.

To implement the movement of the file pointer, the file object provides a tell function and a seek function. The tell function is used to determine the current position of the file pointer, and the seek function is used to move the file pointer to the specified position of the file.

Python Tell Function

The use of the tell function is simple, and its basic syntax is as follows:

File.tell()

Where file represents a file object.

For example, in the same directory, write the following program to read the a.txt file. The content in the a.txt file is:

www.freelearningpoints.com

The code to read a.txt is as follows:

f = open("a.txt",'r')
print(f.tell())
print(f.read(2))
print(f.tell())

The output is:

0
ww
2

It can be seen that when the file is opened using the open function, the starting position of the file pointer is 0, which means that it is located at the beginning of the file. After reading 2 characters from the file using the read function, the file pointer moves to the same time. And moved by 2 characters. This shows that when the program uses the file object to read and write data, the file pointer will automatically move backwards: how many data is read and written, the file pointer will automatically move backwards by as many positions.

Python Seek Function

The seek function is used to move the file pointer to the specified position. The syntax of this function is as follows:

file.seek (offset [, whence])

The meaning of each parameter is as follows:

  • file: indicates a file object;
  • offset: indicates the offset from the file pointer of the whence position, a positive number indicates a backward offset, and a negative number indicates a forward offset. For example, when == 0 && offset == 3 (that is, seek (3,0)), it means that the file pointer moves to the position 3 characters away from the beginning of the file; when == 1 && offset == 5 (that is, seek (5 , 1)) means that the file pointer moves backwards to 5 characters from the current position.
  • whence: As an optional parameter, it is used to specify the position where the file pointer is to be placed. There are 3 options for the parameter value: 0 for the file header (default), 1 for the current position, and 2 for the end of the file

Note that when the offset value is non-zero, Python requires that the file must be opened in binary format, otherwise an io.UnsupportedOperation error will be thrown.

The following program demonstrates file pointer operations:

f = open ('a.txt', 'rb')
# Determine the position of the file pointer
print (f.tell())
# Read a byte, the file pointer automatically moves back by 1 data
print (f.read(1))
print (f.tell())
# Move the file pointer from the beginning of the file to the 5 character position
f.seek(5)
print (f.tell())
print (f.read(1))
# Move the file pointer from the current position to the 5 character position
f.seek (5, 1)
print (f.tell())
print (f.read(1))
# Move file pointer from end of file to 10 characters
f.seek (-1, 2)
print (f.tell())
print (f.read(1))


The output is:

0
b'w
1
5
5
b'r'
11
11
b'r'
25
25
b'm'

Note: Because seek is used in the program, a non-zero offset is used, so the file must be opened with b, otherwise an io.UnsupportedOperation error will be reported, and interested readers can try it for themselves.

The above program demonstrates using the seek method to move the file pointer, including counting from the beginning of the file, the current position of the pointer, and the end of the file. Run the above program and combine the output of the program to experience the effect of the file pointer movement.

                               


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression


More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises