Python Navigating File Object Pointer
Navigating the file object pointer
Python provides seek() function to navigate the file object pointer to the required position specified.
Syntax
//Syntax:
file_object.seek(offset,[whence])
where,
- file_object indicates the file object pointer to be navigated
- offset indicates which position the file object pointer is to be navigated if offset is,
- positive navigation is done in forward direction
- negative navigation is done in backward direction
whence represent reference point for navigating the file object pointer. whence is optional, if not specified default value is 0.
If whence value is
- 0, navigation will take the reference of beginning of file (absolute positioning)
- 1, navigation will take the reference of current position (relative positioning) of the file object pointer
- 2, navigation will take the reference of end of file (relative positioning)
Note : If you are working with is a text file, then the access mode of the should be ‘rb+’ (which opens a file for reading and writing in binary format) otherwise relative positioning will misbehave.
CODE/PROGRAM/EXAMPLE
//Example:
fhr=open("data.txt","rb+")
print(fhr.tell())
fhr.seek(12) #navigates to 12th position from beginning of the file
print(fhr.tell())
fhr.seek(3,1) #navigates to 3rd position from current position of the file object position
print(fhr.tell())
fhr.seek(-3,2)#navigates to 3rd position from end of the file in backward direction
print(fhr.tell())
fhr.close()
Output:
0
12
15
56
File object attributes :
file_object.closed : closed attribute returns true if the file is closed else it will return false.
file_object.mode : mode attribute returns mode in which the file has been opened.
file_object.name : name attribute returns the name of the file opened.
CODE/PROGRAM/EXAMPLE
//Example:
fhr=open("data.txt","rb+")
print("file name:",fhr.name)
print("access mode:",fhr.mode)
print("closed?",fhr.closed)
fhr.close()
print("after closing the file closed?",fhr.closed)
Output:
file name: data.txt
access mode: rb+
closed? False
after closing the file closed? True