0
f = open("food.txt", "r")

for line in f:
    print(line)

I don't understand how the above for loop reads the file line by line? Why not character by character or word by word? please explain.

2
  • 1
    Because it has been decided that it would be so, because there is a lot of data that has to be read line by line. That's all. Commented Dec 6, 2020 at 13:04
  • 1
    do another for loop if you want the characters, for character in line Commented Dec 6, 2020 at 13:04

1 Answer 1

1

That's how Python works, open creates a file-object.

If you look at I/O documentation for file objects by default they read line by line!

In words from documentation: "this is memory efficient, fast, and leads to simple code"

In the previous versions of Python(2.2-), you had to specify byte limit for the same functionality!

For characters you can do:

for line in f: 
    for c in line: print(c)

For words you can do:

for line in f: 
    for w in line.split(): print(w)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.