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.
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.
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)