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

How to set read and write position in a file 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). For example, if there is a file called my_file with text Hello\nworld, and you want to move just before the first l, you can use:

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

This will seek the pointer to just before the first l.