What is the difference between :
with open(\"file.txt\", \"r\") as f:
data = list(f)
Or :
with open(\"file.txt\", \"r\") as
In the 3 cases, you're using a context manager
to read a file. This file is a file object
.
File Object
An object exposing a file-oriented API (with methods such as read() or write()). Depending on the way it was created, a file object can mediate access to a real on-disk file or to another type of storage or communication device (for example standard input/output, in-memory buffers, sockets, pipes, etc.). File objects are also called file-like objects or streams. The canonical way to create a file object is by using the open() function. https://docs.python.org/3/glossary.html#term-file-object
list
with open("file.txt", "r") as f:
data = list(f)
This works because your file object is a stream like object. converting to list works roughly like this :
[element for element in generator until I hit stopIteration]
readlines method
with open("file.txt", "r") as f:
data = f.readlines()
The method readlines() reads until EOF using readline() and returns a list containing the lines.
Difference with list :
You can specify the number of elements you want to read : fileObject.readlines( sizehint )
If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read.
read
When should I ever use file.read() or file.readlines()?