In python when you open a file using
For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code:
#python #file #read #readline #efficiency
open
command the your can read the content of the file. read
will read the whole content of the file at once, while readline
reads the content of the file line by line.NOTE:
if file is huge, read()
is definitely a bad idea, as it loads (without size parameter), whole file into memory.NOTE:
it is good practice to use the with
keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. (We have reviewed with
in depth a couple days ago)NOTE:
read
function gets a size
parameter that specifies the chunks read from a file. If the end of the file has been reached, f.read()
will return an empty string.For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code:
>>>
>>> for line in f:
... print(line, end='')
...
This is the first line of the file.
Second line of the file
#python #file #read #readline #efficiency