4

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.

1
  • 4
    Did you try Googling it? Commented Oct 24, 2015 at 1:01

1 Answer 1

8

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.

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.