Practical 7: Program to open a file read some content check the current position of the file pointer and set the file pointer to a specific position.
Problem Statement
Write a Python program to open a file read some content check the current position of the file pointer and set the file pointer to a specific position.
Solution Code
# Program to demonstrate file pointer position handling
# Open the file in read mode
file = open("sample.txt", "r")
# Read the first 10 characters
content = file.read(10)
print("First 10 characters:", content)
# Get the current file pointer position
position = file.tell()
print("Current file pointer position:", position)
# Move the file pointer to the beginning (0th position)
file.seek(0)
print("File pointer reset to:", file.tell())
# Read the next line from the beginning
line = file.readline()
print("Line after resetting pointer:", line.strip())
# Close the file
file.close()
Output
If sample.txt contains:
Python programming is fun and powerful. File handling is an important concept.
After running the program, the output might be:
First 10 characters: Python pro
Current file pointer position: 10
File pointer reset to: 0
Line after resetting pointer: Python programming is fun and powerful.
Process finished with exit code 0
Explanation
Below is the explanation of F.E. PPS Unit 4 Practical 7 solution where we have written Python program to open a file read some content check the current position of the file pointer and set the file pointer to a specific position.
- Opening the File in Read Mode
- open(“sample.txt”, “r”) opens the file in read mode (r) to read its contents.
- Reading a Specific Number of Characters
- file.read(10) reads the first 10 characters of the file.
- Getting the Current File Pointer Position
- file.tell() returns the current position of the file pointer.
- Resetting the File Pointer
- file.seek(0) moves the file pointer to the beginning (0th position).
- Reading a Line After Resetting
- file.readline() reads the next full line from the file after resetting the pointer.
- Closing the File
- file.close() ensures the file is properly closed after operations.
Key Concepts Learned
- File Pointer (tell())
- The tell() function helps in determining the current position of the file pointer.
- Seeking (seek())
- seek(0) resets the pointer to the beginning of the file, allowing re-reading from the start.
- Efficient File Handling
- Understanding how to manipulate the file pointer improves efficiency in large file processing.