The concept of file handling is used to preserve the data or information generated after running the program. Like other programming languages like C, C++, Java, Python also support file handling.
Refer the below article to understand the basics of File Handling.
seek() function is used to change the position of the File Handle to a given specific position. File handle is like a cursor, which defines from where the data has to be read or written in the file.
Syntax: f.seek(offset, from_what), where f is file pointer
Offset: Number of postions to move forward
from_what: It defines point of reference.
Returns: Does not return any value
The reference point is selected by the from_what argument. It accepts three values:
- 0: sets the reference point at the beginning of the file
- 1: sets the reference point at the current file position
- 2: sets the reference point at the end of the file
By default from_what argument is set to 0.
Note: Reference point at current position / end of file cannot be set in text mode except when offset is equal to 0.
Example 1: Let’s suppose we have to read a file named “GfG.txt” which contains the following text:
"Code is like humor. When you have to explain it, it’s bad."
20 When you have to explain it, it’s bad.
Example 2: Seek() function with negative offset only works when file is opened in binary mode. Let’s suppose the binary file contains the following text.
b'Code is like humor. When you have to explain it, its bad.'
47 , its bad.
- Python PIL | Image.seek() Method
- Wand function() function in Python
- Python - Call function from another function
- Python | dir() function
- id() function in Python
- Python map() function
- Python str() function
- Python | hex() function
- ord() function in Python
- Python | oct() function
- Python tell() function
- sum() function in Python
- Python | now() function
- Help function in Python
- Python | cmp() function
- Python | How to get function name ?
- Python | int() function
- How to Call a C function in Python
- Python | randint() function
- Python - cmath.tan() function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.