Is there a difference between : “file.readlines()”, “list(file)” and “file.read().splitlines(True)”?

  • A+
Category:Languages

What is the difference between :

with open("file.txt", "r") as f:     data = list(f) 

Or :

with open("file.txt", "r") as f:     data = f.read().splitlines(True) 

Or :

with open("file.txt", "r") as f:     data = f.readlines() 

They seem to produce the exact same output. Is one better (or more pythonic) than the other ?

 


Explicit is better than implicit, so I prefer:

with open("file.txt", "r") as f:     data = f.readlines() 

But, when it is possible, the most pythonic is to use the file iterator directly, without loading all the content to memory, e.g.:

with open("file.txt", "r") as f:     for line in f:        my_function(line) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: