Python program to read character till a count

Here, we are going to learn how to read character till a count in Python?
By Shivang Yadav Last updated : July 05, 2023

File Handling in Python is reading and writing data from files. Programs can interact with files and data using the concept of file handling.

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

Python file handling programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.