ADVERTISEMENT
ADVERTISEMENT

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?
Submitted by Shivang Yadav, on March 15, 2021

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.

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 »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.