Home > Article > Backend Development > How to use the seek() method to operate files in Python
This article mainly introduces the tutorial for using the seek() method to operate files in Python. It is the basic knowledge for introductory learning of Python. Friends who need it can refer to it
Seek() method in partial Move sets the current location of the file. The parameter is optional and defaults to 0, which means absolute file positioning, if its value is 1, it means seeking relative to the current position, and 2 means relative to the end of the file.
No return value. Note that if the file is opened or appended using 'a' or 'A', any seek() operation will be undone on the next write.
If the file is only open for writing using 'a' append mode, this method is essentially a no-op, but with read enabled (mode 'a'), it still opens the file in append mode very it works.
If the file uses "t" in text mode, only the offset returned by tell() is legal. Using other offsets can result in undefined behavior.
Please note that not all file objects are searchable.
Syntax
The following is the syntax of the seek() method:
fileObject.seek(offset[, whence])
Parameters
Offset -- This is the position of the read/write pointer in the file.
whence -- This is optional, defaults to 0, which means absolute file positioning, other values are 1, which means seeking relative to the current position, 2 means Relative to the end of the file.
Return value
This method does not return any value.
Example
The following example shows the use of the seek() method.
#!/usr/bin/python # Open a file fo = open("foo.txt", "rw+") print "Name of the file: ", fo.name # Assuming file has following 5 lines # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line line = fo.readline() print "Read Line: %s" % (line) # Again set the pointer to the beginning fo.seek(0, 0) line = fo.readline() print "Read Line: %s" % (line) # Close opend file fo.close()
When we run the above program, it will produce the following results:
Name of the file: foo.txt Read Line: This is 1st line Read Line: This
Related recommendations:
Python study notes-open() function opens the file path and reports an error
The above is the detailed content of How to use the seek() method to operate files in Python. For more information, please follow other related articles on the PHP Chinese website!