In: Computer Science
In python explain why would we want to read a file line by line instead of all at once?
Answer.
Step 1
In python readline() method returns one line from the file in the form of a string. We can also use the parameter as n which specifies the maximum number of bytes we can use. It will be efficient when reading a large file of fetching all data at once, it fetches line by line. This method returns the next line of the file which contains a newline character in the end. Also, if we reached the end of the file, it will return an empty string.
Step 2
Syntax: file.readline()
Example of readline() using while loop
# Python program to demonstrate readline()
L = ["Made\n", "Easy\n", "Publications\n"]
# Writing to a file
file1 = open('myfile.txt', 'w')
file1.writelines((L))
file1.close()
# Using readline()
file1 = open('myfile.txt', 'r')
count = 0
#using while loop
while True:
count += 1
# Get next line from file
line = file1.readline()
# if line is empty
# end of file is reached
if not line:
break
print("Line{}: {}".format(count, line.strip()))
file1.close()
INPUT/OUTPUT:
Kindly upvote please,
Thank you.