
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Locating File Positions in Python
Locating file positions in Python means identifying the current position of the file pointer within an open file. Python provides the tell() and seek() methods of the file object for this task.
Locating the File Position
The tell() method tells you the current position within the file. In other words, it specifies that the next read or write will occur at that many bytes from the beginning of the file.
Example
The following example shows how to get the current file position using the tell() method. Initially, when a file is opened, the pointer is placed at the beginning. After reading a specific number of characters, the file pointer moves forward by that number. The example below demonstrates the same.
# Create a file data = """Python is a great language. Yeah its great!!""" with open("foo.txt", 'w') as f: f.write(data) # Open the file fo = open("foo.txt", "r") # Get current file position position = fo.tell() print("Current file position before Read():", position) # Read first 5 characters data = fo.read(5) print("Read string is:", data) # Get current file position position2 = fo.tell() print("Current file position after read():", position2) # Close the file fo.close()
Output of the above program is as follows ?
Current file position before Read(): 0 Read string is: Pytho Current file position after read(): 5
Changing the File Position
The seek(offset[, whence]) method of the file object changes the current file position. The offset argument indicates the number of positions to be moved.
Example
This example demonstrates getting and changing the file position using the tell() and seek() methods.
# Create a file data = """Python is a great language. Yeah its great!!""" with open("foo.txt", 'w') as f: f.write(data) # Open the file fo = open("foo.txt", "r+") # Read first 4 characters data = fo.read(4) print("Read string is :", data) # Check current position position = fo.tell() print("Current file position : ", position) # Reposition pointer at the beginning once again position = fo.seek(0, 0) data = fo.read(10) print("Read string again :", data) # Again check current position position2 = fo.tell() print("Current file position : ", position2) # Close opened file fo.close()
This produces the following result ?
Read string is : Pyth Current file position : 4 Read string again : Python is Current file position : 10