5

When using python 3.5 os.walk() and looking at the dirname output I get a lot of empty lists (returned [ ]). I have no idea why.

import os
tdir = '/home/pontiac/testdir'

gen0 = os.walk(tdir)
print(next(gen0)[1])
print(next(gen0)[1])

gen1 = os.walk(tdir)

for ea in gen1:
    print(ea[1])

Output:

['t2', 't1']

[]

['t2', 't1']

[]

[]
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
user3163030
  • 313
  • 5
  • 12

3 Answers3

4

Quoting from Python Documentation:

os.walk(top, topdown=True, onerror=None, followlinks=False)
Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).

Since testdir has only two empty directories t1 and t2, so you will get :

>>> import os
>>> t = '/home/pontiac/testdir'
>>> for root, dirs, files in os.walk(t):
    print root, dirs, files


/home/testdir ['t1', 't2'] []
# ^rootdir     ^dirs list  ^files in rootdir 
/home/testdir/t1 [] []
/home/testdir/t2 [] []
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
2

According to os documentation what os.walk returns is a 3-tuple (dirpath, dirnames, filenames).

Let's say you have a directory testdir:

testdir
      |- dir1
      |    |- file3.txt
      |- dir2
      |- file1.txt
      |- file2.txt

Then looping over generator returned by os.walk('path/to/testdir') will produce the following tuples:

('path/to/testdir', ['dir2', 'dir1'], ['file3.txt', 'file1.txt', 'file2.txt'])
('path/to/testdir/dir2', [], [])
('path/to/testdir/dir1', [], ['file3.txt'])

Since you're extracting first elements from the 3-tuples and getting empty lists, that means these are directories that contain no subdirectories in them.

vrs
  • 1,922
  • 16
  • 23
0

The call os.walk returns a tuple (dirpath, dirnames, filenames). You print the [1] element of this tuple, dirnames, which is the list of subdirectories in a given directory. Your directories t1 and t2 apparently do not contain any subdirectories, hence the empty lists.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
  • This turns into a lot! of empty lists when I walk over a directory that has a fair amount of depth to it. I get 30 + in a row, I'm confused about what is the point of this. If I am trying to use this part os.walk, and am looking to get the directory names, if a directory has no subdirectories I don't need the none existent names? – user3163030 Jan 01 '16 at 13:40