I have finished pset5 and now on pset6 but I have one doubt about how we can read the file without file.read() or readlines() etc.

I understand both code

file = open(“testfile.txt”, “r”) 
c = file.read()


with open('file.txt') as fp:
    lines = fp.read()

But how this can work, how can for loop read file without reading

file = open(“testfile.txt”, “r”) 
for line in file: 

Even David M uses formeathod in week 8 lectures to port speller load function in python.
If this is features then how both are different?


Python file objects are also iterators, that's how for uses them. It keeps calling the iterator's next method, which spits out a single line at a time.

Just don't combine this implicit next and any kind of read.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .