Q:

Python program to read first N character from each line

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now