Here are sample Python code snippets on the usage of tell() and seek() in Python. Using tell (), you will know the current position in the file, and you can set it as you wish using seek().
Logic to Use tell()
The current position in the file can be known with the help of ‘tell()’ function. It returns the file object’s present position in the form of an integer. In binary mode, the position is represented as the number of bytes from the beginning of the file. In text mode, the position is represented as an opaque number.
Initially the text in the file is "I AM READY" >>> str=myfile.read(10) Result is "I AM READY" >>> pos=myfile.tell() >>> print("present position of the file: ", pos) Result present position of the file: 10
Logic to Use seek()
The current position of the file can be changed with the help of the ‘seek()’ function. It indicates the number of bytes to be moved and the point from where the bytes must move.
Syntax: ‘seek(offset[, from])‘
- The ‘offset’ argument specifies the number of bytes to be moved.
- The ‘from’ argument indicates the reference position, starting from where the bytes are to be moved.
- The file beginning is used as the reference position if ‘from’ is set as 0.
- The current file position is used as the reference position if ‘from’ is set as 1.
- The file end is used as the reference position if ‘from’ is set as 2.
I am now changing the offset and from position >>> pos=myfile.seek(0,0) >>> print("The text from updated position: ", pos) The text from updated position: I AM READY
- How to Derive Year from DATEs Useful MySQL Query
- Linux How To Understand These BOOT, START, SHUTDOWN
- How to Define Various VSAM Clusters with IDCAMS