- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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
The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the current position as the reference position and if it is set to 2 then the end of the file would be taken as the reference position.
Let us take a file foo.txt, which we created above.
#!/usr/bin/python # Open a file fo = open("foo.txt", "r+") str = fo.read(10) print "Read String is : ", str # Check current position position = fo.tell() print "Current file position : ", position # Reposition pointer at the beginning once again position = fo.seek(0, 0); str = fo.read(10) print "Again read String is : ", str # Close opend file fo.close()
This produces the following result −
Read String is : Python is Current file position : 10 Again read String is : Python is
- Locating Modules in Python
- Locating and executing Python modules (runpy)
- Positions of Large Groups in Python
- Locating child nodes of WebElements in selenium.
- Selenium Webdriver Locating Strategies By Class Name
- File Objects in Python?
- What are the different Welding Positions?
- Program to find number of special positions in a binary matrix using Python
- Junk File Organizer in Python?
- File Upload Example in Python
- Design File System in Python
- Python file parameter in print()?
- How can I source a Python file from another Python file?
- File Searching using Python
- How do we find the exact positions of each match in Python regular expression?