opening text file in 'r' mode and printing the list( <filehandle> ) gives a list of all lines

Viewed 20

I recently, by mistake, found out that if I print out the list( filehandle ) in python for a file open in 'r' mode, it print out a list of all lines of the file.

File trial.txt:

12345
67890
abcd

Code:

a = open("trial.txt", 'r')
print( list(a) )

Output:

['12345\n', '67890\n', 'abcd']

Can anyone explain why this happens?

1 Answers

File implements python interators functions: __next__ & __iter__

When you make a list of out of file handle, these will be called by list and populate it with the data from the file.

Related