root
----dir1
--------file1
--------file2
--------dir2
------------file3
--------dir3
-------------dir4
------------------file4
----file5
So the above would return:
[root/dir1/file1, root/dir1/file2, root/dir1/dir2/file3, etc...]
I've been trying different ways of using os.path.walk() for that, but
I can't find an elegant way. Anyone know of something simple to
accomplish that?
Try this:
file_list = []
for root, _, filenames in os.walk(root_path):
for filename in filenames:
file_list.append(os.path.join(root, filename))
for x in file_list:
print x
It's not magic at all. _ is just a variable name. When someone names a
variable _, it's just to let you know that they won't actually be
using that variable. In this case, os.walk returns three things: the
root, the list of directories, and the list of files. You only need
two of those for your code, so you ignore the third.
The underscore is no magic here. It's just a conventional variable
name, saying "I m unused". One could also write:
for root, UNUSED, filenames in os.walk(root_path):
...
BTW. Please quote enough of the posts you reply to. Most people
access this list/newsgroup per mail client or usenet reader, not per
a webpage, so without quoting, they might not see the context of our
post. Thank you.
What does the notation "_" stands for ? Is it a sort of /dev/null ?
I know that in the terminal it represents the last printed text.
Laurent
It's a convention for saying "I don't really care about this
particular value which is returned from that function". You
could, at your whim, use "dontcare" or "x" or whatever.
TJG
> > file_list = []
> > for root, _, filenames in os.walk(root_path):
> > for filename in filenames:
> > file_list.append(os.path.join(root, filename))
>
> What does the notation "_" stands for ? Is it a sort of /dev/null ?
>>> x, _, y = 1, "hukairs", 3
>>> x, y
(1, 3)
>>> _
'hukairs'
>>>