Computer >> Computer tutorials >  >> Programming >> Python

How to use seek() method to reset a file read/write position in Python?


You can use the seek(offset[, whence]) method. It sets the file's current position, like stdio's fseek(). The whence argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file's end).

Example

For example, if you already have a file open and want to go back to starting position, you can use:

f = open('my_file.txt', 'r')
f.seek(0)
f.close()

This will seek the pointer to beginning of the file. You can also provide the second argument as 2 and get the pointer to end of file.