Reputation: 168
I don't understand why do the test1 and test2 will return 2 different output when they are the same.
python3.7.4
fin=open('D:\Python\Think Python\words.txt')
def build_list_append(file):
word_list=[]
for line in fin:
word=line.strip()
word_list.append(word)
return word_list
def test1(worklist1=build_list_append(fin)):
print("This is test1,It will return a non-empty list")
print(len(worklist1))
def test2(worklist2=build_list_append(fin)):
print("This is test2,It will return an empty list")
print(len(worklist2))
Upvotes: 0
Views: 47
Reputation: 1098
Short Answer: That's because once
test1()
is called, read pointer will move to end of file. Oncetest2()
is called there are no lines left to read, hence0
length.
Long Answer:
At fin = open('D:\Python\Think Python\words.txt')
the read pointer will point at the beginning of the file.
Once file1()
is called, it will call build_list_append(fin)
which will iterate through the file line-by-line. Because of this all lines will be store in word_list
and length will be returned.
Now, the pointer is pointing at the end of the file.
After calling test2()
, program again calls build_list_append(fin)
which want to iterate through whole file line-by-line, but since pointer is already at end of the file it doesn't have any content to go through. Hence, length 0 is returned.
If you try closing the file and pass a fresh file object, test2()
will return same value as test1()
.
Upvotes: 1
Reputation: 24691
Try running the program again, except with the fin = open(...)
statement inside the function build_list_append()
(make sure to add a fin.close()
at the end as well). Then, they'll act the same.
File objects in python (those returned by open()
) belong to a class of object called a generator*. Generators are iterable, and lazily return element after element as necessary. What differentiates them from, say, lists, is that you can't go backwards in a generator - you can only ever get the next element. So when you run out of elements, you get nothing.
That's what's happening here. The loop for line in fin
exhausts all the elements that the file object can produce, the first time it's executed. When you execute it again, the generator has no more to give, and so the for
loop doesn't run, and you get an empty list. Unless you re-create the generator from the start, by calling open()
again, it has run out of elements.
*it's more complicated than this, and technically file objects aren't generators, but they act sufficiently similar to draw the comparison.
Upvotes: 0