Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between file.read(), file.readline() and iterating over the file object [duplicate]

Tags:

python

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.

like image 300
Korrupted Studios Avatar asked Feb 08 '23 17:02

Korrupted Studios


1 Answers

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.

like image 89
woot Avatar answered Feb 15 '23 09:02

woot