The file pointer is a cursor that indicates the current position in the file from where the next read or write will happen.
Python provides two main methods to control the file pointer:
- tell(): Returns the current position of the file pointer.
- seek(offset, whence): Moves the file pointer to a specified position.
Understanding file pointers helps in reading and writing files more efficiently.
फाइल पॉइंटर एक कर्सर होता है जो फाइल में वर्तमान स्थिति को दर्शाता है जहाँ अगली पढ़ाई या लिखाई होगी।
Python में फाइल पॉइंटर को नियंत्रित करने के लिए दो मुख्य मेथड्स हैं:
- tell(): वर्तमान फाइल पॉइंटर की स्थिति बताता है।
- seek(offset, whence): फाइल पॉइंटर को निर्दिष्ट स्थान पर ले जाता है।
फाइल पॉइंटर को समझना फाइलों को प्रभावी ढंग से पढ़ने और लिखने में मदद करता है।
5 Examples of Using File Pointer in Python
Example 1: Using tell() to Find Current Position
with open('sample.txt', 'r') as file:
print('Initial position:', file.tell())
content = file.read(10)
print('Position after reading 10 chars:', file.tell())
Output: Initial position: 0
Position after reading 10 chars: 10
tell() returns the byte position of the pointer. Initially 0, after reading 10 characters, it moves to 10.
tell() फाइल पॉइंटर की स्थिति बताता है। शुरू में 0 होता है, 10 अक्षर पढ़ने के बाद 10 हो जाता है।
Example 2: Using seek() to Move Pointer to Start
with open('sample.txt', 'r') as file:
file.read(10)
print('Position before seek:', file.tell())
file.seek(0)
print('Position after seek to start:', file.tell())
Output: Position before seek: 10
Position after seek to start: 0
seek(0) moves the pointer back to the beginning of the file.
seek(0) फाइल पॉइंटर को फाइल की शुरुआत में ले जाता है।
Example 3: Using seek() with offset to Move Pointer
with open('sample.txt', 'r') as file:
file.seek(5)
print(file.read(5))
Output: Prints 5 characters starting from byte 5.
seek(5) moves pointer to 5th byte; reading 5 chars from there.
seek(5) पॉइंटर को 5वें बाइट पर ले जाता है; वहां से 5 अक्षर पढ़ता है।
Example 4: Using seek() with whence=2 to Move Pointer from End
with open('sample.txt', 'rb') as file:
file.seek(-5, 2) # 2 means from file end
print(file.read())
Output: Reads last 5 bytes of the file.
seek(-5, 2) moves pointer 5 bytes before end; reads last 5 bytes.
seek(-5, 2) फाइल के अंत से 5 बाइट पीछे जाकर पढ़ता है।
Example 5: Combining seek() and tell() to Read Specific Part
with open('sample.txt', 'r') as file:
file.seek(3)
print('Position:', file.tell())
print('Read:', file.read(7))
Output: Position: 3
Read: (7 characters starting from 4th byte)
Moves pointer to byte 3, prints position, and reads 7 chars from there.
पॉइंटर को 3 बाइट पर ले जाकर स्थिति दिखाता है और 7 अक्षर पढ़ता है।