I am new to computer science and am trying to create a function in python that will open files on my computer.
I know that the function f.readline()
grabs the current line as a string, but what makes the functions f.read()
and for line in f:
different? Thanks.
read(x)
will read up to x bytes in a file. If you don't supply the size, the entire file is read.
readline(x)
will read up to x bytes or a newline, whichever comes first. If you don't supply a size, it will read all data until it hits a newline.
When using for line in f
, it will call the next()
method under the hood which really just does something very similar to readline
(although I see references that is may do some buffering more efficiently since iterating usually means you are planning to read the entire file).
There is also readlines()
which reads all lines into memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With