Tech C**P
15 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
In python when you open a file using 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