0

Can someone explain the usage of the _ in this for loop?

for dirs,_,files in os.walk(directory):
   for f in files:
       yield os.path.abspath(os.path.join(dirs, f))

My goal is to get the filenames with full path recursively. I got this from another question and it does exactly what I want. But I don't understand it.

Kevin Lemaire
  • 642
  • 9
  • 30
  • `_` is just like any variable like `a` or `b` but by convention it means we don't care about it. Also, `_` will return the most recent output from a Python Interactive Session even though it wasn't stored in any variable – Vineeth Sai Oct 25 '18 at 09:05
  • the [entry in the doc](https://docs.python.org/3/library/os.html#os.walk) explained the output of `os.walk`, a 3-tuple: `(dirpath, dirnames, filenames)`. so the unpacking done there is for `dirnames` – deadvoid Oct 25 '18 at 09:07

1 Answers1

1

os.walk returns the tuple (root, dirs, files) where

  • root: the current directory
  • dirs: the files in the current dir
  • files: the files in the current dir

if you do not use one of these variables in your subsequent loop, it is customary to call it _ (or even append a name such as _dirs). that way most IDEs will not complain that you have assigned a variable but you are not using it.

in your example you could do:

for root, _dirs, files in os.walk(directory):
    pass

and the IDE should not complain that you are not using the variable _dirs.

hiro protagonist
  • 36,147
  • 12
  • 68
  • 86