In the
Python learning Session of this article today, let's look at
python file positioning. In the next article I'll tell my friends what the file locator is in Python and what this file location can do.
File location
The tell () method tells you the current position within the file, in other words, the next read and write will occur after so many bytes at the beginning of the file.
The Seek (offset [, from]) method changes the position of the current file. The offset variable represents the number of bytes to move. The from variable specifies the reference position at which to begin moving bytes.
If from is set to 0, this means that the beginning of the file is used as the reference location for moving bytes. If set to 1, the current position is used as the reference location. If it is set to 2, then the end of the file will be used as the reference location.
Example:
#!/usr/bin/python#-*-coding:utf-8-*-# open a file fo = open ("Foo.txt", "r+") str = fo.read () print "Read the string is:", str# find the current bit Position = Fo.tell () print "Current file location:", position# reposition the pointer again to the beginning of the file position = Fo.seek (0, 0) str = fo.read (+) print "Reread string: ", str# close Open file Fo.close ()
The result of the above example output:
The string read is: The current file location for TE: 10 re-read string: This is te