Why does this work with or without `.readlines()`?

what is the different from these command…?

with open("how_many_lines.txt") as lines_doc:
  for line in lines_doc.readlines():
    print(line)

and

with open("how_many_lines.txt") as lines_doc:
  for line in lines_doc:
    print(line)

both of them have same output:

1. How many lines do we write on the daily,

2. Many money, we write many many many

3. How many lines do you write on the daily,

4. Say you say many money, you write many many many

i mean, what’s actually function from .readlines() if without it, still produce same output…?

thanks …

2 Likes

I too would like to know.

If you are working with a lengthy text (millions of lines, perhaps), you might not want to upload and insert into memory a list of every line, as you would using the file.readlines() approach. for line in file:, on the other hand, loads and works with only one line at a time.

4 Likes

If not using for line in file: is more efficient with larger files, why does file.readlines() exist? for line in file: seems to get the job done faster, with less code, and be more readable.

2 Likes

Does anyone have an answer to butter_coder’s question? I’m curious as well.

@butter_coder IANAE, but the reason for file.readlines() to exist is to create a list of lines from the file, each being stored as a string.

1 Like

A simple test could clearly illustrate the difference.

interests.txt

I love piano.

I love painting.

Python

fr=open(‘interests.txt’)

fr.read() # ‘I love piano.\nI love painting.\n’

fr=open(‘interests.txt’)

fr.readlines() # [‘I love piano.\n’,‘I love painting.\n’]

1 Like