What is the difference between :
with open(\"file.txt\", \"r\") as f:
data = list(f)
Or :
with open(\"file.txt\", \"r\") as
They're all achieving the same goal of returning a list of strings but using separate approaches. f.readlines()
is the most Pythonic.
with open("file.txt", "r") as f:
data = list(f)
f
here is a file-like object, which is being iterated over through list
, which returns lines in the file.
with open("file.txt", "r") as f:
data = f.read().splitlines(True)
f.read()
returns a string, which you split on newlines, returning a list of strings.
with open("file.txt", "r") as f:
data = f.readlines()
f.readlines()
does the same as above, it reads the entire file and splits on newlines.