Andriy Andriy - 1 month ago 12
Python Question

Strange behaviour of Python list() function with a file object argument

Trying to pass a file object to

list
function cannot get the list of file objects.

x = open('example.txt', 'rb')
y = list(x)


And the output is
y = ['aaaaa']
, whereas I expected to get a list of file objects:
[<open file 'example.txt', mode 'rb' at 0x7fa03ced1300>]
containing only one element, of course. Why
list
function have transformed its argument here?

Answer

Iterating through a file object iterates through the lines in the file.

Usual usage:

for line in f:
    # do something with the line

The argument to list constructor is an iterable. The argument will be iterated and the list will be created from iterated items.

Usage example:

list('abc')  # result: ['a', 'b', 'c']

That combined, list(f) creates a list of lines read from the file.

To actually create a list containing one file object do this:

list_of_files = [f]