Python › File I/O & Context Managers
What is the difference between reading a file with .read(), .readline(), and .readlines()?
BeginnerAnswer
read() returns the ENTIRE file's contents as a single string; readline() returns just the NEXT single line (including its trailing newline); readlines() returns a LIST of every line in the file — read() and readlines() both load the whole file into memory at once.
with open("data.txt") as f:
all_content = f.read() # one big string
with open("data.txt") as f:
first_line = f.readline() # just one line
with open("data.txt") as f:
lines = f.readlines() # a list of every lineReal-world example Choosing readline() to process a huge file one line at a time versus read() for a small file you need entirely at once.