python - Trying to Print List: Getting Empty -
here code:
>>> f=open('list.txt') >>> print list(f) ['bird\n', 'cat\n', 'cat\n', 'cat\n', 'tree'] >>> mylist=list(f) >>> print mylist [] >>> print list(f) [] why list empty??? earlier in code shows list correct list. further, why first command "print mylist" showing empty list? had set mylist=list(f). thanks.
because read whole file. once have read file, file pointer has been moved end , no more data 'found' beyond point.
re-open file or seek start:
f.seek(0) note first line print list(f); exhausted file iterator (moved file pointer end of te file).
your next statement mylist=list(f), tries read f again. file pointer still @ end of file, no data returned when reading , empty list created.
Comments
Post a Comment