Python program to read first N character from each line

Here, we are going to learn how to read first N character from each line in Python?
By Shivang Yadav Last updated : July 05, 2023

Reading data from a file is done using file handling which allows the program to interfere with the files and store or retrieve data from it.

Read first N character from each line

For reading data line by line from a file in python we have an inbuilt method readline(). Using this method, we will extract a line from the file and then print only the first N characters of the line.

Python program to read first N characters from each line

# Program to read first N character 
# from each line in python 

import time

# Opening the file
File = open('file.dat','r')

while(True):
    # Reading line using readline()
    data = File.readline()
    if(data==''):break
    #  Printing only 2 character from each line 
    print(data[0:2],end=' ')
    time.sleep(0.3)

File.close()

File : File.dat

Hello!
Learn Python Programming At Inclduehelp.com
Python is a easy to learn

Output

He Le Py 

Explanation

In the above code, we have read data from a file named "file.dat". We have read data line by line using readline() method and stored it into data named collection. And then printed only the first 2 lines from the data.

Python file handling programs »

Comments and Discussions!

Load comments ↻





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