Well, what is the nature of your dircontent
?
>>> import os
>>> os.scandir()
<posix.ScandirIterator object at 0x7f2e3b329f80>
It is not a list, nor a tuple or one of the data types that you might have learnt about. It is a special kind of object, of which the type is posix.ScandirIterator
. The most important property of this object is that it supports the “iteration protocol”. Essentially, this means that you can use the object in a for
loop:
for filename in os.scandir():
...
So, lists and tuples support iteration, but there are many more types supporting it too. In fact, you can even define your own (search “python define iterator” in any search engine). An iterator has an internal state that it uses to yield successive elements. In this case, the ScandirIterator
might be using some OS function to get the files one by one. Most importantly, it has not yet gotten the name of next file before you process the current one.
So, at the end of your first comprehension, the dircontent
iterable is exhausted – you have iterated over it once, and it is done with iterating now, as it has given all elements. If you need the scandir result several times, you have to create a new iterable:
dircontent = os.scandir()
txtfiles = [... for f in dircontent if ...]
dircontent2 = os.scandir()
mp4files = [... for f in dircontent2 if ...]
Alternatively, you can convert the iterable to a list first. The list()
builtin exhausts the iterable, exactly like a for
loop does, and puts all of the elements in a memory structure that holds them, available for reuse.
dircontent = list(os.scandir())
txtfiles = [...]
mp4files = [...]