To read characters from file till a specific character count from the current pointer position, we will use read() method and pass the count as parameter.
To get back to the starting position, we will use seek() method.
Program to read data from file till a specific position
# Python program to read character till a count
# main function
def main():
# opening the file in read mode.
file = open("data.txt","r")
# printing file name
print("Name of the File : ",file.name)
# reading 10 characers
String = file.read(10)
print("Read String is till 10 : ",String)
position = file.tell()
print("Current Position : ",position)
String =file.read(10)
print("Read String is till next 10 : ",String)
position = file.tell()
print("Current Position : ",position)
print()
print("Sending Pointer back to Top")
position = file.seek(0,0)
print("Current Position : ",position)
String =file.read(25)
print("Read String is till 25 : ",String)
position = file.tell()
print("Current Position : ",position)
file.close()
if __name__=="__main__":main()
File : File.dat
learn python programming language at inclduehelp.com
Output:
Name of the File : data.txt
Read String is till 10 : learn pyth
Current Position : 10
Read String is till next 10 : on program
Current Position : 20
Sending Pointer back to Top
Current Position : 0
Read String is till 25 : learn python programming
Current Position : 25
Program to read data from file till a specific position
File : File.dat
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer