I am learning file handling in python right now. If i write read() method , it does work same as readline() method . There must be a difference between them and i want to learn that
-
`read()` reads all of the file's contents into a string, `readline` reads just a single line from the file – C.Nivs Aug 26 '19 at 18:15
-
2https://docs.python.org/3/library/io.html#io.IOBase – CristiFati Aug 26 '19 at 18:15
-
What was unclear in the documentation and your research? – Sayse Aug 26 '19 at 18:16
-
oh i see now . If I use "\n" in a line , the readline() method will stop reading – Noor Muhammad Light Aug 26 '19 at 18:17
2 Answers
This question has been answered countless times, and the documentation does a good job of describing the differences, too. But here goes:
If you have a file (test.txt
) like so:
first line
second line
third line
Then this code:
with open("test.txt", "r") as file:
line = file.readline()
print(line)
Will produce this output:
first line
That's because readline
just reads the next line.
If you use this code instead:
with open("test.txt", "r") as file:
content = file.read()
print(content)
Output:
first line
second line
third line
read()
reads the entire contents of the file into a string.
You can also give read()
an optional argument, which designates the number of characters to read from the file:
with open("test.txt", "r") as file:
content = file.read(15)
print(content)
Output:
first line
seco
Finally, the third function, which you didn't mention, is readlines
, which returns a list of lines (strings):
with open("test.txt", "r") as file:
lines = file.readlines()
print(lines)
Output:
['first line\n', 'second line\n', 'third line\n']

- 10,481
- 2
- 9
- 15
-
There are a ton of other subtleties here. Like how subsequent calls to `readline` return subsequent lines, and that *both* consume the file handle, just at different rates. OP might expect to be able to do `fh.read(); fh.read()` and both be the same, but they will not be – C.Nivs Aug 26 '19 at 18:26
-
The main difference is that read() will read the whole file at once and then print out the first characters that take up as many bytes as you specify in the parenthesis versus the readline() that will read and print out only the first characters that take up as many bytes as you specify in the parenthesis. You may want to use readline() when you're reading files that are too big for your RAM.

- 141
- 6