adrian.andreas
adrian.andreas

Reputation: 39

Why is os.walk() not defining dirs or files?

I have this code in Python 2.7:

# !/usr/bin/python

import os
root=os.path.normpath('/home/andreas/Desktop/')

print root
for root, dirs,files in os.walk(root, topdown=True):
    break   
print(files)

Which works. It returns a list with the filenames in Desktop. But when I change the path like:

 root=os.path.normpath('/home/andreas/Desktop/Some_Dir')

I get this error:

NameError: name 'files' is not defined

This applies also for dirs.

What could be the problem?

Upvotes: 2

Views: 2397

Answers (1)

schesis
schesis

Reputation: 59238

If dirs and files are not defined after your for loop terminates, that means os.walk() didn't yield any results – which means they never got assigned any value, and so remain undefined.

Here's a simple example of the same effect in action:

>>> for x in []:  # empty
...     pass
... 
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

>>> for x in [1, 2, 3]:
...     pass
... 
>>> x
3

The obvious explanation for os.walk(some_path) not yielding any results is that some_path doesn't exist or is inaccesible ... so presumably you don't have a Some_Dir, or you don't have permission from the OS to access it.

For example:

$ mkdir nope
$ chmod a-rwx nope
$ python
Python 2.7.13 (default, Jan 13 2017, 10:15:16) 
[GCC 6.3.1 20161221 (Red Hat 6.3.1-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> for root, dirs, files in os.walk('nope'):
...     break
... 
>>> dirs
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'dirs' is not defined
>>> files
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'files' is not defined
>>> 

Upvotes: 2

Related Questions